Bg1987
Bg1987

Reputation: 1159

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.

Upvotes: 32

Views: 48878

Answers (5)

Richard J. Ross III
Richard J. Ross III

Reputation: 55533

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)

Upvotes: 51

Cornstalks
Cornstalks

Reputation: 38218

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.

Upvotes: 21

Bg1987
Bg1987

Reputation: 1159

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.

Upvotes: 3

Mahesh
Mahesh

Reputation: 34625

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

Upvotes: 2

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506847

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.

Upvotes: 0

Related Questions