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

Categories

I wanna create a global object in cpp program, how do I do that? Is this right? in "global_obj.h"

#include "class.h"
Class obj;

in "main.cpp"

extern Class obj;
See Question&Answers more detail:os

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

1 Answer

We declare our globals as extern in a header file, in your case: global_obj.h, and the actual global variable in a source file: global_obj.cpp. In separate source files we #include "global_obj.h" to have access to them.

It should look like this:

global_obj.cpp

Class obj;

global_obj.h

extern Class obj;

main.cpp

#include "global_obj.h"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...