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.
Related
I'm stuck in a linker error and need some help. I'm using MSVC.
At the beginning, I made this:
/* graphics_app.h */
#ifndef DK_GRAPHICS_APP_H
#define DK_GRAPHICS_APP_H
...
class GraphicsApp {
private:
static GraphicsApp* self;
...
};
GraphicsApp* GraphicsApp::self = nullptr;
#endif /* DK_GRAPHICS_APP_H */
This header used to work... and I made some improvements, but nothing about that static member changed.
but unexpectedly I got this linker error message:
LNK2005 "private: static class GraphicsApp * GraphicsApp::self" (?self#GraphicsApp##0PEAV1#EA) already defined in main.obj.
LNK1169 one or more multiply defined symbols found.
So, I separated this header into .h and .cpp:
/* graphics_app.cpp */
#include "graphics_app.h"
...
GraphicsApp* GraphicsApp::self = nullptr;
but I got another error:
LNK2001 "private: static class GraphicsApp * GraphicsApp::self" (?self#GraphicsApp##0PEAV1#EA) unresolved external symbol.
LNK1120 1 unresolved externals.
Why these weird behavior happens & how can I fix?
EDIT:
I made test version to make problem simper.
This thing happens when I use my custom include directory...
such as
#include <dk/graphics_app.h>
instead of
#include "graphics_app.h"
So.. a new problem is, how can I fix this whilst using my custom include directory?
Edit2:
To make Thing much simpler..
LNK2005:
This error happened because, the header file was included in two other cpp files (compiled to obj files) . Then when the linker tried to link the obj it found two of the same definitions. But "there can be only one"!
Because of this ambiguity the linker gives up.
LNK2001:
This error happened because the linker did not find the defined variable in any obj file. So I think that the new cpp is missing from your project definition.
This header used to work... and I made some improvements, but nothing about that static member changed.
Your header is written incorrectly: you are not supposed to put definitions of entities with external linkage into header files. It could "work" as long as you included your header file into one and only one translation unit. But once you include it into two or more different translation units, you get the "multiple definition" error. Which is exactly what happened in your case.
So, I separated this header into .h and .cpp
This is the right thing to do. Now you have to make sure your graphics_app.cpp is compiled (and linked) as part of your program. This is something you forgot to do. The compiler/linker/build system cannot somehow "magically" realize by itself that your freshly created graphics_app.cpp is supposed to be part of your project.
I have visual studio solution which contains various of C++ projects. For simplicity there are two projects. One for .lib and another for .exe. Both project use precompiled header stdafx.h. But precompiled header is shared between projects.
Recently somebody placed definition of variable inside stdafx.cpp and because it is shared between projects I got:
error LNK2005: "int x" (?x##3HA) already defined in stdafx.obj
So my question is: Is it ok to put definitions into precompiled header? (in cpp part from which is precompiled header created)
I would guess that precompiled header should contain only declarations of symbols and not definitions. Or am I wrong?
Typically you don't want to define a variable in any header.
When a header is included, it is effectively pasted into the including file before compilation starts. This means anything defined in the header will be repeated in every file including the header. This usually compiles just fine, but leaves the linker with the problem of figuring out which definition is the real definition.
If everyone is to share a single x, place
extern int x;
in a header and
int x;
in an appropriate cpp file.
If every includer is to have their own private x
static int x;
goes in the header, but personally I see this as an ugly dodge that you should try to work around.
As to whether it is legal to put stuff other than headers you want precompiled into in stdafx or not, I honestly don't know. Never done it. I do know that it's not how stdafx.h is intended to be used, you only want to put headers from libraries that will not be modified as part of the project in stdafx.h, so I wouldn't do it.
Recommended reading: Purpose of stdafx.h, What's the use for "stdafx.h" in Visual Studio?, and How to use stdafx.h properly?
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 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.
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.