Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

compiler errors - 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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...