c++ multiple definitions of a variable
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
)
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.
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.
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