简体   繁体   English

跟踪LNK2005:“已经定义”

[英]tracking down LNK2005: “already defined”

I have been working on a program in windows VC++ 2008. I started by having all of my code in .cpp files (just to get everything working), and now breaking things into .h, and .cpp files. 我一直在使用Windows VC ++ 2008中的程序进行工作。我首先将所有代码都存储在.cpp文件中(只是为了使所有功能正常工作),现在将内容分为.h和.cpp文件。 when I compile I get a mountain of LNK2005 errors stating that: 当我进行编译时,出现了很多LNK2005错误,指出:

Object.obj : error LNK2005: "__thiscall thing::thing(args)" already defined in otherObject.obj

while I was making the original program I kept getting errors of undeclared identifier, and so I gave a include directive to satisfy that. 在制作原始程序时,我不断收到未声明标识符的错误,因此我提供了一个include指令来满足这一要求。 now when I am breaking everything up into separate .cpp, and .h files I get all of this. 现在,当我将所有内容分解为单独的.cpp和.h文件时,我得到了所有这些。 which place do I start looking (Object, otherObject, or thing), or somewhere else. 我开始寻找哪个地方(对象,其他对象或事物)或其他地方。

Basically you have definition for thing::thing(args) in two Translation Units(TU), which violates the One Definition Rule(ODR) and hence the error. 基本上,您在两个转换单元(TU)中对thing::thing(args)进行了定义,这违反了一个定义规则(ODR),因此违反了错误。
The linker exactly tells you which TU's are involved: otherObject.obj and Object.obj . 链接器准确地告诉您涉及哪个TU: otherObject.objObject.obj

Start looking in to otherObject.cpp and Object.cpp and the headers which are included in these two cpp files. 开始查找otherObject.cppObject.cpp以及这两个cpp文件中包含的标头。 It is most likely that you have defined your constructor thing::thing(args) in header file and including that header file in both these cpp files results in multiple definitions. 您很可能已经在头文件中定义了构造函数thing::thing(args) ,并且在这两个cpp文件中都包含该头文件会导致多个定义。

Suggested Solution: 建议的解决方案:

You cannot define the constructor in header file, You need to add it to your cpp file along with other member functions of the class. 您无法在头文件中定义构造函数,需要将其与该类的其他成员函数一起添加到cpp文件中。 If you must add the definition of constructor to header you should mark it inline , given that You have not shown your code I don't see any reason to apply the second approach. 如果必须将构造方法的定义添加到标头,则应将其标记为inline ,因为您尚未显示代码,所以我看不出有任何理由使用第二种方法。

Given the information in your question, I bet that the method is defined in a header file but not marked inline. 给定您问题中的信息,我敢打赌该方法在头文件中定义,但未标记为内联。 This then causes duplicate symbol linker errors. 然后,这将导致重复的符号链接器错误。 Try marking hte method inline or moving the definition to a source ( .C ) file. 尝试内联标记方法,或将定义移至源( .C )文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM