Question

I have 3 files in a Visual Studio project: test.cpp, date.cpp and main.cpp -

test.cpp:

int g() { return 0; }

date.cpp:

/*totally empty*/

main.cpp:

#include "test.cpp"
#include "date.cpp"

int main() { return g(); }

I understand that defining functions in a header file leads to violation of One-Definition Rule if header file is called multiple times. But here, I am calling it only once from only one file/translation unit. Why is it still throwing LNK2005?

Was it helpful?

Solution 2

You are including "test.cpp" in "main.cpp" - this is most likely wrong, as Visual Studio will ALSO compile "test.cpp" as a separate file, and then link "test.obj" with "main.obj" (those are the files generated by the compiler) into "main.exe". When it then finds "g()" in both "test.obj" and "main.obj", it says "Huh? Why have you got two of these" (or, in linker terms "multiple defined symbols").

The solution is to have a "test.h" that declared void g(); and then use that to include into "main.cpp".

OTHER TIPS

You should not include test.cpp and date.cpp. Instead, you should write test.h and date.h, and include it:

test.h

int g();

date.h

// Contains prototypes for functions inside date.cpp

main.cpp

#include "test.h"
#include "date.h"

int main() { return g(); }

Since test.cpp is in the VS Project, it will be compiled and lined in along with main.cpp causing the multiple definitions - unless you take special measure to prevent that from happening, like removing test.cpp from the project or setting it to be "Excluded from Build".

If you rename temp.cpp to test.h you get two benefits:

  1. VS will not automatically compile a .h when it's in a project, since it assumes that the file is intended to be included from other files instead of being stand-alone compiled.
  2. it will be less confusing to programmers about the intended use of the files
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top