LNK2005, LNK1169 errors, “int __cdecl g(void)” (?g@@YAHXZ) already defined

可紊 提交于 2019-12-11 18:52:40

问题


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?


回答1:


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".




回答2:


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(); }



回答3:


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


来源:https://stackoverflow.com/questions/16256046/lnk2005-lnk1169-errors-int-cdecl-gvoid-gyahxz-already-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!