Take the 2-minute tour ×

I have 4 files (2 headers, and 2 code files). FileA.cpp, FileA.h, FileB.cpp, FileB.h


#include "FileA.h"

int main()
    return 0;

void hello()
    //code here


#ifndef FILEA_H_
#define FILEA_H_
#include "FileB.h"
void hello();

#endif /* FILEA_H_ */


#include "FileB.h"

void world()
    //more code;


#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.

share|improve this question
Welcome to the world of linking.. –  Richard J. Ross III Jun 17 '12 at 15:00
add comment

5 Answers

up vote 5 down vote accepted

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:


extern int wat;


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)

share|improve this answer
This answer was enlightening. –  Wolfer Aug 29 '13 at 18:39
add comment

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

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
share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer


