C++ LNK2005 'already defined' errors - files referencing themselves

3.3k Views Asked by At

I have inherited a C++ solution with 3 projects, one compiling to a .DLL, the other two to .EXEs . The DLL builds on its own fine, but the other two, when built, produce around 65 LNK2005 errors, the majority of which are referencing the same .obj file, as shown in the log exert below:


Linking...
Function.obj : warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/OPT:ICF' specification
Function.obj : error LNK2005: _ReadLocalRegister already defined in Function.obj
Function.obj : error LNK2005: _getSource already defined in Function.obj
Function.obj : error LNK2005: _SendLogEvent already defined in Function.obj
Function.obj : error LNK2005: _DebugMsg already defined in Function.obj
Function.obj : error LNK2005: _MyInformationMsg already defined in Function.obj
MyNTService.obj : error LNK2005: "public: __thiscall CMyNTService::CMyNTService(void)" (??0CMyNTService@@QAE@XZ) already defined in MyNTService.obj
MyNTService.obj : error LNK2005: "public: virtual void __thiscall CMyNTService::OnStop(void)" (?OnStop@CMyNTService@@UAEXXZ) already defined in MyNTService.obj
MyNTService.obj : error LNK2005: "public: void __thiscall CMyNTService::SaveStatus(void)" (?SaveStatus@CMyNTService@@QAEXXZ) already defined in MyNTService.obj

....and so it goes on!

I am a C# coder, only basic C++ knowledge, so I am lost with this. The solution is an 15 year old C solution I am attempting to rebuild as a C++ solution in VS2008. I have managed to build it once, nothing has changed, but perhaps some config settings have changed since then.

Does anyone have ideas where I could start to look...?

Many thanks!

2

There are 2 best solutions below

0
On

It sounds like you're missing inclusion guards on the header file for that object.

Add:

#ifndef SomeUniqueName
#define SomeUniqueName

//Code goes here.

#endif

Wrapping the code in the header file. The compiler will go through that header file many times when processing your code as it's included in many places (most likely). The inclusion guards stop redefinition of things that have already been defined on previous passes.

PS: It also might help to do a "make clean". Makefiles can be finnicky especially if not made 100% right and sometimes when dependencies are off you need to clean before rebuilding.

0
On

in msvc110 (2012), I encountered the same error and the only workaround i found was to create a class and a separate DLL for the recurrent functions I used in the different files. Here's the link to do so.

Cheers