DebugUtil.h
#ifndef DEBUG_UTIL_H
#define DEBUG_UTIL_H
#include <windows.h>
int DebugMessage(const char* message)
{
const int MAX_CHARS = 1023;
static char s_buffer[MAX_CHARS+1];
return 0;
}
#endif
When I try to run this I get this error:
Terrain.obj : error LNK2005: "int
__cdecl DebugMessage(char const *)" (?DebugMessage##YAHPBD#Z) already
defined in Loodus.obj
Renderer.obj : error LNK2005: "int
__cdecl DebugMessage(char const *)" (?DebugMessage##YAHPBD#Z) already
defined in Loodus.obj
test.obj : error LNK2005: "int __cdecl
DebugMessage(char const *)"
(?DebugMessage##YAHPBD#Z) already
defined in Loodus.obj
C:\Users\Tiago\Desktop\Loodus
Engine\Debug\Loodus Engine.exe : fatal
error LNK1169: one or more multiply
defined symbols found
But why does this happen? I have #ifndef #define and #endif in the header so multiple definitions shouldn't happen
Put the definition (body) in a cpp file and leave only the declaration in a h file. Include guards operate only within one translation unit (aka source file), not across all your program.
The One Definition Rule of the C++ standard states that there shall appear exactly one definition of each non-inline function that is used in the program. So, another alternative would be to make your function inline.
Make the function inline or declare the function in a header file and define it in a cpp file.
inline int DebugMessage(const char* message)
{
const int MAX_CHARS = 1023;
static char s_buffer[MAX_CHARS+1];
return 0;
}
EDIT:
As a comment by Tomalak Geret'kal suggests, it's better to use my latter suggestions than my former and move the function's declaration to a cpp file.
(Assuming the posted code is a header, included from multiple .cpp files)
Header guards do not protect you from link-time multiple definitions. Regardless that you have ensured the header will only appear once per Translation Unit, if you have more than one Translation Unit then that's still multiple definitions.
Write definitions in source files, and only declarations in headers.
The only exceptions are inline functions, functions defined within a class definition (though this is not recommended!) and function templates.
This function is included into every translation unit and as a result you get multiple definitions of it - each .obj file contains its own copy. When it's time to link them all together the linker rightfully shows the above error.
You can do a few things:
Move the definition to a .cpp file and keep only the declaration in the header.
Use an anonymous namespace around the function in your header file (but realize it's a hack - you will still have multiple definitions, just no name collision).
Mark it as inline (although it might not always work - only if the compiler actually chooses to inline it). That's also a hack for the same reason as above.
That only prevents multiple inclusions in the same source file; multiple source files #includeing it will still generate multiple definitions of DebugMessage(). In general, you should either not place functions in header files at all or make them static (and usually inline, since otherwise it doesn't usually make sense to have multiple static definitions of the same function).
100% Certain you correctly included Guards but still getting redefinition error?
For Visual Studio:
I was really frustrated because I was correctly included guards,
only to find out the problem was visual studio. If you have added the file
to your project, the compiler will add the file twice even if you have
include guards around your implementation file and header file.
If you don't use visual studio exclusively, and say... use code::blocks sometimes, you might want to only #include the file when you detect the absence of the visual studio environment.
DebugUtil.h :
----------------------
#ifndef _WIN32
#include "DebugUtil.c"
#endif
----------------------
If you are okay with including stdio.h,
you can be a little less hackish about it:
DebugUtil.h :
----------------------
#include <stdio.h>
#ifdef _MSC_VER
#include "DebugUtil.c"
#endif
----------------------
Reference:
Predefined Macros, Visual Studio:
https://msdn.microsoft.com/en-us/library/b0084kay.aspx
Move the definition to a .cpp file.
Declare your functions in C++ files. Since you defined your function in the header file, and that header file is included from multiple source files, it gets defined for each source file that includes it. That's why it's reported as being defined in multiple places.
Alternatively, you could make it inline so that the code is inserted wherever it's used instead of being defined as a separate function each time.
It looks like you are including DebugUtil.h in more than one translation unit, then linking those objects together. However, DebugUtil.h provides a definition for the DebugMessage function, so that definition exists in all of the translation units that incorporated the header. As a result, when you link the objects, the linker rightly complains that the symbol is multiply defined.
Change DebugUtil.h so that it declares DebugMessage via a prototype, but does not provide a definition, and place the definition of DebugMessage in a .c file which you will compile and link with your other objects.
Related
I have two files as below:
Test1.h
#ifndef TEST_H
#define TEST_H
int i = 10;
#endif
Test2.cpp
#include <iostream>
#include "Test1.h"
int main()
{
std::cout << i << std::endl;
}
I know I can solve this by using extern or const in Test1.h.
But my question is that "I don't understand the error".
error LNK2005: "int i" (?i##3HA) already defined in Test1.obj
error LNK1169: one or more multiply defined symbols found
How can int i have multiple definitions?
The header file has include guards.
When I include the header file it should mean that everything gets copied in Test2.cppand it should become:
Test2.cpp
#include <iostream>
int i = 10
int main()
{
std::cout << i << std::endl;
}
And header file should become irrelevant at this point after everything being included.
My other question is if I declare int i with extern in header file and include it in .cpp, then would it be an example of external linkage? Because generally I have seen external linkage between two .c or .cpp as in here but if you explicitly include the file is it still regarded as i having external linkage?
Each compilation unit (a .cpp file) produces its own set of symbols individually which are then linked together by the linker.
A header file "becomes" part of the compilation unit it is included in, which compile to an object file (.obj in Windows, .o in Unix systems)
Therefore it is like you have defined a global 'i' in each compilation unit.
The correct solution (as you know, if you have to have a global) is to declare it as "extern" in the header then have one compilation unit actually define it.
Include guards only prevent the same header being included twice in the same compilation unit, which can happen if I include and and one of those includes the other.
How can int i have multiple definitions?
The file that has the definition was included in multiple translation units (cpp file). One unit was compiled into the object file Test1.obj. The source of the other unit is shown in your answer (Test2.cpp). The error is shown when you try to link the object files together.
The header file has include guards.
That prevents the contents of the file from being repeated within a single translation unit. It makes no difference to separate units.
My other question is if I declare int i with extern in header file and include it in .cpp, then would it be an example of external linkage?
extern makes the linkage external explicitly. But even without extern, variables declared in the namespace scope have implicit external linkage by default (there are exceptions). The difference in this case is that extern variable declarations are not definitions unless there is an initializer.
I can achieve external linkage without including header file i.e. with two .cpp files by making a variable extern in one .cpp and defining it in other and linker finds its definition. But if I have one header file with extern variable and include it in other .cpp does this count as external linkage?
It does not matter how the extern declaration ends up in the cpp file. Whether it was included from a header or not, it declares a variable with external linkage.
Probably you are trying to create the executable file from two unit of translations.
Your error shows that the object have been defined in Test1.obj. Probably, your program is Test1.obj+Test2.obj, and both files include the same definition, which has external linkage.
Do you have other Test1.cpp in your project that also include the Test1.h ?
If not, do you do any config to your compiler so it also build the .h files to object files ?
The reason can just be the answer of one of two questions above.
When I include the header file it should mean that everything gets copied in Test2.cpp and it should become:
Yes and then you do the exact same thing in Test1.cpp (which you didn't show us).
Hence, multiple definitions.
I got a class exported in dll. And got inline functions in that exported class:
Header.h
class MODULE_EXPORT A
{
public:
int GetInt(){ return iSomeInt; }
};
When I include that header file in a seperate module. I Got error LNK2005 which means: GetInt() already defined.
If I put the function definition in .cpp file . NO error occurs.
GetInt is inline function if I define it that way in the header file ,right? so why the redefinition linking error? I use the vc++ compiler. (Visual Studio 2010).
EDIT:
#pragma once
has already been added to the header file. Forgot to mention that.
Essentially for a function definition in a header file is visible to every compilation unit and they attempt to compile it.
However the function is already defined in the dll.
The solution would be place the definition in the cpp file as you noted or to use the static keyword so the definition is only visible to the compilation unit it's defined in and not ones that include it.
Also inlining functions is only a performance hint for the compiler, it may not inline it. And for this function I can't imagine their being any performance benefits given it's simplicity so I'd recommend moving it into the .cpp file.
I have created custom random number generators and placed their global functions in a file I called SamRandom.h. The file looks as follows:
#ifndef _SAM_RANDOM_H
#define _SAM_RANDOM_H
#include <cstdlib>
#include <ctime>
void InitialiseRandomSeed()
{
//...
}
//...
#endif
I'm working in a very complex object-oriented program that has many different components from here and there. Everytime I add a file that is anyhow related to this file, I get the following conflict message:
LaserBase.obj:-1: error: LNK2005: "void __cdecl InitialiseRandomSeed(void)" (?InitialiseRandomSeed##YAXXZ) already defined in main.obj
error: LNK1169: one or more multiply defined symbols found
On MSVC, and on MinGW I get:
In function `Z20InitialiseRandomSeedv':
SamRandom.h:8: multiple definition of `InitialiseRandomSeed()'
error: first defined here
:-1: error: collect2: ld returned 1 exit status
Why is this happening? I thought that preprocessor directive is supposed to prevent this problem from happening... this is really driving me crazy!!!
P.S.: The problem is independent of the function name.
Thanks for any efforts
When you include your file in a .cpp file the preprossesor directly copys it into that file. So when you compile that .cpp file the object file (a step the compiler always does even if you don't recognize) will contain that function. If you include it in more than one .cpp file each object file will contain the function. When the linker trys to link all object files to an executable it finds the function x-times and gives that error.
"one or more multiply defined symbols found" says it found one of your functions (or variables) more than once and doesnt know how to deal with it.
To avaoid this you should only put the signature of you function e.g.
//whatever.h
#ifndef _SAM_RANDOM_H
#define _SAM_RANDOM_H
void InitialiseRandomSeed();
#endif
in ther header file and put the implementation into a seperate .cpp file:
//whatever.cpp
#include "whatever.h"
#include <cstdlib>
#include <ctime>
void InitialiseRandomSeed()
{
//...
}
The header guards ensure that the function is not being defined multiple times in a single compilation unit (.cpp file). However, they don't prevent the function from being defined a single time in multiple compilation units. This is because the header contains the definition of the function, so every .cpp that includes the header has its own definition of the function.
You could move the definition to SamRandom.cpp and instead declare the function in the header like so:
void InitialiseRandomSeed();
Alternatively you could specify that the function is inline which would make multiple definitions acceptable:
inline void InitialiseRandomSeed()
{
//...
}
Assuming that the function is not performance-critical and does not get called frequently, I would go with the former approach. This keeps headers more readable and (in general) decreases compile times.
You could separate the definition into a .cpp file and just declare the function in the header.
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. when I compile I get a mountain of LNK2005 errors stating that:
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. now when I am breaking everything up into separate .cpp, and .h files I get all of this. 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.
The linker exactly tells you which TU's are involved: otherObject.obj and Object.obj.
Start looking in to otherObject.cpp and Object.cpp and the headers which are included in these two cpp files. 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.
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. 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.
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.
I had a big main .cpp file with everything in it .I needed to break the code and so I created a helper.h where I moved all the typedefs, function declarations etc.Now I am trying to move some of the functions from main .cpp into helper.cpp .I had a global called mypoint* originalpoint[mypoint is a stucture I defined in helper.h].I moved it into helper.h and placed one of the functions that uses it into helper.cpp .It is throwing this error now :-
Error 1 error LNK2005: "struct mypoint * originalpoints" (?originalpoints##3PAUmypoint##A) already defined in Main.obj Helper.obj Stereo002
Error 2 fatal error LNK1169: one or more multiply defined symbols found C:\Documents and Settings\Raj\My Documents\Visual Studio 2008\Projects\Stereo002\Debug\Stereo002.exe 1 Stereo002
I am not sure why is it saying multiply defined.I have everything in helper.h .I include helper.h into main.cpp and helper.cpp.
You put the creation of a variable into the .h file, so it's being created in both .cpp files.
The way to fix this is to declare it as extern in the .h file, and duplicate it without the extern in one of the .cpps.
In this case, since your header is included in two places, the compiler will create an instance of that variable for each time it is included. When the linker runs next, it finds two definitions for 'originalpoint' and complains.
Mark's answer is correct - in order to work around this issue, you can specify the variable as having external linkage by declaring it 'extern', which tells the linker to look for the declaration of this variable elsewhere (in one of the cpp files). Then, you actually declare it in one of the cpp files.
It is worth confirming that this is indeed what you want - one variable shared between the two files. Since they were originally part of the same implementation file, this is probably the desired effect.