Archived

This topic is now archived and is closed to further replies.

radjan_spirit

c++ global variables

Recommended Posts

I''m using Visual C++ 6 and having a real sonofabitch time declaring global variables; here''s my situation: -It is a large win32 application performed with many classes across many .h and .cpp files. -There are three global variables defined in a .h file that every other file gets access to via #include''s -There are two global functions (WinMain,WndProc) declared in a .h file and defined in a .cpp file that no other files include (very bottom of the #include heirarchy) anyway, if I declare my global variables this way: bool g_baKeys[256]; I get this error for every single class: Grid.obj : error LNK2005: "bool * g_baKeys" (?g_baKeys@@3PA_NA) already defined in GameManager.obj if I make the variables static: static bool g_baKeys[256] then the program behaves as is there is a different instance of the variable in each class and each program thread (MsgProc sees different values from WinMain). och, aye. msdn not helped so far, how does one solve such problems on such a compiler? Thank you tons in advance, I''ve been ripping my hair out all night. Radjan

Share this post


Link to post
Share on other sites
Using globals is a pretty nasty way of avoiding well-thought-out design, but here''s what to do.

Declare the global in ONE .c file like this:
bool g_baKeys[256];

Then in the other .c files that use it, do this:
extern bool g_baKeys[];

This is how it''s done, but that doesn''t make it right. I suggest restructuring to put the key array where it belongs, and have functions to get key state.

- Pete

Share this post


Link to post
Share on other sites
a global variable has to exist somewhere in one object file

object files are (basically) what you get when you compile a .cpp file

so you need your global variable in one .cpp file

then declare it in some header file as ''extern''

if you want to use the global in a cpp file somewhere then include the header

when the program is linked it''ll find the extern variable in the one object

ta da

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
In C++ you can create a Singleton Class to store the globals variables of your program and share them across every modules.

Share this post


Link to post
Share on other sites