'c++ multiple definitions of a variable
I have 4 files (2 headers, and 2 code files). FileA.cpp, FileA.h, FileB.cpp, FileB.h
FileA.cpp:
#include "FileA.h"
int main()
{
hello();
return 0;
}
void hello()
{
//code here
}
FileA.h:
#ifndef FILEA_H_
#define FILEA_H_
#include "FileB.h"
void hello();
#endif /* FILEA_H_ */
FileB.cpp:
#include "FileB.h"
void world()
{
//more code;
}
FileB.h:
#ifndef FILEB_H_
#define FILEB_H_
int wat;
void world();
#endif /* FILEB_H_ */
when I try to compile(with eclipse), I get " multiple definition of `wat' " And I don't know why, it seems as it should work just fine.
Solution 1:[1]
I'm not going to include all of the details, but you define a global variable, wat twice in your compilation uint.
To fix, use the following:
FileB.h
extern int wat;
FileB.cpp
int wat = 0;
This (extern) tells the compile that the variable wat exists somewhere, and that it needs to find it on it's own (in this case, it's in FileB.cpp)
Solution 2:[2]
Don't declare the variable in the header. #include literally copies and pastes the contents of the file into the other file (that is, any file that does #include "FileB.h" will literally copy the contents of FileB.h into it, which means int wat gets defined in every file that does #include "FileB.h").
If you want to access wat from FileA.cpp, and it's declared in FileB.cpp, you can mark it as extern in FileA.cpp.
Solution 3:[3]
I found the answer now (I guess looking at the files one after another helped) The problem is that the compiler creates a FileB.o which has a definition of wat, and then it tries to compile FilB.o with FileA.cpp, while FileA.h has an include of FileB.h it will now also have a definition of wat.
Solution 4:[4]
You get multiple definition because wat is declared at file scope and get's visible twice in the 2 source files.
Instead, make the variable declartion extern and define it in exactly one source file.
extern int wat; // In FileB.h
int wat; // In FileB.cpp
Solution 5:[5]
That wat variable declaration is a definition that should belong in a cpp file. It is as if you would put your function bodies into the header.
You need to put extern before the wat declaration and copy your current declaration without the extern into one of the cpp files.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Cornstalks |
| Solution 3 | Bg1987 |
| Solution 4 | Mahesh |
| Solution 5 | Johannes Schaub - litb |
