How to declare global variable in this situation? [duplicate]
Possible Duplicate:
What is the correct way of using extern for global variables ?
Sorry for repeating a similar question.
//object.h
object p;
//b.h
#include object.h
//b.cc
extern object p;
//c.h
#include object.h
#include b.h
//c.cc
extern object p;
//main.cc
#include c.h
extern object p;
int main() {}
Basically I need c
b
and main
all have access to object p
. I also need c to have access to the methods in b and b c to have access to Object class header. What is the way to declare global variable p? The code above gives me Multiple definition error. I can't post the entire code for it would be too long, but I believe the above describes the sit开发者_如何学Pythonuation well.
Declare the global variable in just one of the .cc
files. Put its extern
declaration in the corresponding .h
file, and then include that file in every other .cc
that needs to access the global variable.
In that way, the variable will be declared in every .cc
(thanks to the extern
declaration #include
d from the .h
), but will be defined only in a single .cc
.
On the other hand, you should never define global variables in headers, otherwise you will get multiple definition errors during the linking (unless they had internal linkage, i.e. they were declared as static
, but you won't ever need to have a static
variable defined in a header).
By the way, remember to use include guards in your headers to avoid multiple definition errors during the compilation stage.
精彩评论