In visual studio 2012 I have a small console c++ project with the following code
Main.cpp:
#include "../TestLib/LibFunction.h"
int _tmain(int argc, _TCHAR* argv[])
{
int number = libFunction(7);
return 0;
}
and in a static library project LibTest I have LibFunction.h:
#pragma once
int libFunction( int a );
LibFunction.cpp
int libFunction( int a )
{
return a + 1;
}
This compiles and runs fine. (The Library is added as a reference and linked in implicitly)
If I now add this code to main project
int libFunction( int a )
{
return 7 * a;
}
when I try to build the program I get this error
Main.obj : error LNK2005: "int __cdecl libFunction(int)" (?libFunction@@YAHH@Z) already defined in TestLib.lib(LibFunction.obj)
which is fair enough. However if I now just try building again ( doing nothing else ) the link completes without error and the program runs fine with the new libFunction being used.
Why does the error go away? Why is there this inconsistency? Either it is valid to override a function in a library or its not. I should not get an error and then without doing anything get no error.
I am trying to understand the behaviour for a much larger project where again there are duplicate symbols defined in the exe and referenced lib and sometimes I get errors and sometimes not.