symbol is multiply defined [duplicate] - c++

This question already has answers here:
linux gcc linker problems with C program
(3 answers)
Closed 10 years ago.
I have a .h file
test.h
std::list<std::string> RegisterList;
I want to access this list in 2 .c files
A.c
#include "test.h"
RegisterList.push_back(myString);
B.c
#include "test.h"
RegisterList.push_back(myString2);
When i compile this code, i get an error
ld: fatal: symbol `RegisteredList' is multiply-defined:
What can be the problem ? Is RegsiterList is initialized by default in test.h which is leading to this problem ?

Because you defined the object in the header file and violated one definition rule. Never define objects in header file.
If you want to use a global object, You need to declare it as extern and define it in one and only one source file.

You need something like:
test.h
extern std::list<std::string> RegisterList;
A.c
#include "test.h"
RegisterList.push_back(myString);
B.c
#include "test.h"
std::list<std::string> RegisterList;
RegisterList.push_back(myString2);

Your code goes through a chain: preprocessor -> compiler -> linker. Your problem originates with the preprocessor, but doesn't show up until the linker.
#include is a pre-processor directive.
Instead of compiling your .cpp file, the preprocessor synthesises another file from it, pasting in any included files.
The compiler then compiles the synthetic file producing an object file which contains data definitions, among other things.
You direct the preprocessor to #include the header file in two different .cpp files, which produces two different object files with the same data defined.
ld: fatal: symbol 'RegisteredList' is multiply-defined
This error message is the linker (ld) complaining that a global symbol is defined multiple times, and it doesn't know which one to use.

Don't instantiate the variable in a header file. Always instantiate it in a code file, and refer to the instantiation in a header file.

Related

Why "int i" has multiple definitions?

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.

one or more multiply defined symbols found error - simple

I'm trying to deal with this problem for some time and I can't seem to find the solution. I'm getting error:
one or more multiply defined symbols found
I faced this error while dealing with something more complicated, but even simple examples like this one don't work for me. Here is my main.cpp:
#include "defs.cpp"
int main()
{
string a = "A";
printIt(a);
}
, and here is my defs.cpp:
#include "header.h"
void printIt(string a)
{
cout << a;
}
, and this is my header.h:
#include <string>
#include <iostream>
using namespace std;
void printIt(string a);
I guess this is something trivial, but please don't rage if you think this is duplicate, because I'm a beginner and I didn't understand more complicated examples. Some help would be appreciated.
When you see #include "defs.cpp" you need to get very suspicious: cpp files are not meant to be included; only header files are designed for that.
Instead of including a cpp file, write a header for it. It appears that you have a suitable header already - your header.h, which contains the forward declaration of printIt:
void printIt(string a);
Now replace #include defs.cpp with #include "header.h", and compile your code. This should fix the problem.
Compiling this depends on the system where you are trying it out. On UNIX-like systems, you would write
g++ defs.cpp main.cpp
./a.out
You should not #include a CPP file. Only include header files containing the function prototype definitions. If no such header file exists, put the function prototype in your program (for eg. in file where main is written).
In your case, you are including (directly/indirectly) the CPP file which is having the definition of the function. Since same definition is compiled through CPP files, compiler is putting them into .OBJ file (known as intermediate or object files). The linker finally attempts to combine these Object files, and says some function (symbol) is multiply defined.
In main.cpp you are including defs.cpp which includes a definition of printIt. So the translation unit corresponding to main.cpp defines printIt.
However, you are also compiling defs.cpp which defines printIt. defs.cpps corresponding translation unit thus defines printIt too.
Combining both into one program would lead to multiple (yet equivalent) definitions of this function which is forbidden by the ODR. Remove the #include directive and your program should link correctly.
This is because you are including:-
#include "defs.cpp"
and due to this there are multiple definitions of method printIt.
These are some basic rules:-
1) You must always include only header files in your source files. Even then you have to make sure header files are included only once because if it is included more than once then there could again be problem of multiple definition.To protect against that your header files should contain header gaurds.
2) C++ always adheres with single definition rule. However , you can have as many declaratons as possible as long as all declarations are consistent.

How can the order of include statements matter in the linking step?

I cannot explain the behaviour I am seeing when linking my code. Maybe someone has an idea what's going on...
I have a multiple file C++ project which uses GNU automake tools as its build system (all on Linux).
After adding a source and header file (lets call them util.cc and util.h) to the project and having an already existing source file (calc.cc) calling a function from the newly added files I get a linking error depending on where the include statement appears. I repeat: The error occurs in the linking step, compilation runs fine!!
Example:
I get an error when putting the new include statement at the end of the preexisting statements, like:
calc.cc:
#include "file1.h"
#include "file2.h"
#include "file3.h"
#include "file4.h"
#include "util.h" // new header
This version compiles fine. But linking produces an error (symbol not found)!!
Now, when changing this to
#include "util.h" // new header
#include "file1.h"
#include "file2.h"
#include "file3.h"
#include "file4.h"
then compilation and linking runs fine!
Since the linker only reads the .o files, this must mean that different content is produced depending on where the include statement appears. How can this be?
Compiler is g++ (GCC) 4.4.6
Chances are that util.h has a #define that changes the behaviour of one of the other files.
Your best chance of working out exactly what is going on would involve examining those header files for the name of the missing symbol and getting the pre-processor output from compiling calc.cc both 'working' and 'non working' way, and comparing the two files.
Simple, header files can (re)define macros which can change the interpretation of later macros.
For instance, in your example above, if file1.h does
#define lseek lseek64
and util.h has an inline function which calls lseek, then depending on the include order the generated object code will have a symbol reference to lseek or lseek64.
Which is why projects tend to have rules that config.h (generated by autoconf) is included first.
You're absolutley right: different object code is produced in the two cases. As #hmjd also points out, most likely there's a macro in util.h which one of the other (.h or .c) files use, and any undeclared, called identifier is assumed to be a function by the compiler -- this is most likely the error here.

C++: File conflicting with itself

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.

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

I have always seen people write
class.h
#ifndef CLASS_H
#define CLASS_H
//blah blah blah
#endif
The question is, why don't they also do that for the .cpp file that contain definitions for class functions?
Let's say I have main.cpp, and main.cpp includes class.h. The class.h file does not include anything, so how does main.cpp know what is in the class.cpp?
First, to address your first inquiry:
When you see this in .h file:
#ifndef FILE_H
#define FILE_H
/* ... Declarations etc here ... */
#endif
This is a preprocessor technique of preventing a header file from being included multiple times, which can be problematic for various reasons. During compilation of your project, each .cpp file (usually) is compiled. In simple terms, this means the compiler will take your .cpp file, open any files #included by it, concatenate them all into one massive text file, and then perform syntax analysis and finally it will convert it to some intermediate code, optimize/perform other tasks, and finally generate the assembly output for the target architecture. Because of this, if a file is #included multiple times under one .cpp file, the compiler will append its file contents twice, so if there are definitions within that file, you will get a compiler error telling you that you redefined a variable. When the file is processed by the preprocessor step in the compilation process, the first time its contents are reached the first two lines will check if FILE_H has been defined for the preprocessor. If not, it will define FILE_H and continue processing the code between it and the #endif directive. The next time that file's contents are seen by the preprocessor, the check against FILE_H will be false, so it will immediately scan down to the #endif and continue after it. This prevents redefinition errors.
And to address your second concern:
In C++ programming as a general practice we separate development into two file types. One is with an extension of .h and we call this a "header file." They usually provide a declaration of functions, classes, structs, global variables, typedefs, preprocessing macros and definitions, etc. Basically, they just provide you with information about your code. Then we have the .cpp extension which we call a "code file." This will provide definitions for those functions, class members, any struct members that need definitions, global variables, etc. So the .h file declares code, and the .cpp file implements that declaration. For this reason, we generally during compilation compile each .cpp file into an object and then link those objects (because you almost never see one .cpp file include another .cpp file).
How these externals are resolved is a job for the linker. When your compiler processes main.cpp, it gets declarations for the code in class.cpp by including class.h. It only needs to know what these functions or variables look like (which is what a declaration gives you). So it compiles your main.cpp file into some object file (call it main.obj). Similarly, class.cpp is compiled into a class.obj file. To produce the final executable, a linker is invoked to link those two object files together. For any unresolved external variables or functions, the compiler will place a stub where the access happens. The linker will then take this stub and look for the code or variable in another listed object file, and if it's found, it combines the code from the two object files into an output file and replaces the stub with the final location of the function or variable. This way, your code in main.cpp can call functions and use variables in class.cpp IF AND ONLY IF THEY ARE DECLARED IN class.h.
I hope this was helpful.
The CLASS_H is an include guard; it's used to avoid the same header file being included multiple times (via different routes) within the same CPP file (or, more accurately, the same translation unit), which would lead to multiple-definition errors.
Include guards aren't needed on CPP files because, by definition, the contents of the CPP file are only read once.
You seem to have interpreted the include guards as having the same function as import statements in other languages (such as Java); that's not the case, however. The #include itself is roughly equivalent to the import in other languages.
It doesn't - at least during the compilation phase.
The translation of a c++ program from source code to machine code is performed in three phases:
Preprocessing - The Preprocessor parses all source code for lines beginning with # and executes the directives. In your case, the contents of your file class.h is inserted in place of the line #include "class.h. Since you might be includein your header file in several places, the #ifndef clauses avoid duplicate declaration-errors, since the preprocessor directive is undefined only the first time the header file is included.
Compilation - The Compiler does now translate all preprocessed source code files to binary object files.
Linking - The Linker links (hence the name) together the object files. A reference to your class or one of its methods (which should be declared in class.h and defined in class.cpp) is resolved to the respective offset in one of the object files. I write 'one of your object files' since your class does not need to be defined in a file named class.cpp, it might be in a library which is linked to your project.
In summary, the declarations can be shared through a header file, while the mapping of declarations to definitions is done by the linker.
That's the distinction between declaration and definition. Header files typically include just the declaration, and the source file contains the definition.
In order to use something you only need to know it's declaration not it's definition. Only the linker needs to know the definition.
So this is why you will include a header file inside one or more source files but you won't include a source file inside another.
Also you mean #include and not import.
That's done for header files so that the contents only appear once in each preprocessed source file, even if it's included more than once (usually because it's included from other header files). The first time it's included, the symbol CLASS_H (known as an include guard) hasn't been defined yet, so all the contents of the file are included. Doing this defines the symbol, so if it's included again, the contents of the file (inside the #ifndef/#endif block) are skipped.
There's no need to do this for the source file itself since (normally) that's not included by any other files.
For your last question, class.h should contain the definition of the class, and declarations of all its members, associated functions, and whatever else, so that any file that includes it has enough information to use the class. The implementations of the functions can go in a separate source file; you only need the declarations to call them.
main.cpp doesn't have to know what is in class.cpp. It just has to know the declarations of the functions/classes that it goes to use, and these declarations are in class.h.
The linker links between the places where the functions/classes declared in class.h are used and their implementations in class.cpp
.cpp files are not included (using #include) into other files. Therefore they don't need include guarding. Main.cpp will know the names and signatures of the class that you have implemented in class.cpp only because you have specified all that in class.h - this is the purpose of a header file. (It is up to you to make sure that class.h accurately describes the code you implement in class.cpp.) The executable code in class.cpp will be made available to the executable code in main.cpp thanks to the efforts of the linker.
It is generally expected that modules of code such as .cpp files are compiled once and linked to in multiple projects, to avoid unnecessary repetitive compilation of logic. For example, g++ -o class.cpp would produce class.o which you could then link from multiple projects to using g++ main.cpp class.o.
We could use #include as our linker, as you seem to be implying, but that would just be silly when we know how to link properly using our compiler with less keystrokes and less wasteful repetition of compilation, rather than our code with more keystrokes and more wasteful repetition of compilation...
The header files are still required to be included into each of the multiple projects, however, because this provides the interface for each module. Without these headers the compiler wouldn't know about any of the symbols introduced by the .o files.
It is important to realise that the header files are what introduce the definitions of symbols for those modules; once that is realised then it makes sense that multiple inclusions could cause redefinitions of symbols (which causes errors), so we use include guards to prevent such redefinitions.
its because of Headerfiles define what the class contains (Members, data-structures) and cpp files implement it.
And of course, the main reason for this is that you could include one .h File multiple times in other .h files, but this would result in multiple definitions of a class, which is invalid.