开发者

How to declare global variable in this situation? [duplicate]

开发者 https://www.devze.com 2023-03-18 10:24 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: What is the correct way of using extern for global variables ?
This question already has answers here: Closed 11 years ago.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号