• Advertisement

Archived

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

Global globals?

This topic is 5558 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This is sort of a stupid question but.. What''s the best way to declare global variables that carry across an entire project? I tried making a globals.h and declaring variables normally.. Except I got some error about it already existing in another file, even though it definetly isn''t declared there. (I think what happened is it tried to declare it each time I use included"globals.h" on a file). Any way around this? what''s the best way to do it?

Share this post


Link to post
Share on other sites
Advertisement
In globals.h, declare your variables using the extern keyword.

extern int someGlobalVar;
extern double fooBar;

In one (and only one) source file (globals.cpp?), define your variables.
int someGlobalVar;
double fooBar;

Share this post


Link to post
Share on other sites
used the #ifndef directives?

    
#ifndef __GLOBALS_H__
#define __GLOBALS_H__

int my_global_int;
char my_global_char;
...

#endif


the #ifndef,#define,#endif makes sure the .h file is only read once..


/* Everything IMHO */
-Luctus

[edited by - Luctus on December 5, 2002 10:03:58 AM]

Share this post


Link to post
Share on other sites
You''re right. Any time you #include a .h file in code, the contents of that .h file are actually copied to the code. So you don''t want to have the actual instances of any variables, or functions be in a .h file

If you want a set of stuff to be globally available to everything in the game I''d set it up in a globals.cpp file (the variables) and in globals.h have the externs of the variables. So that any file you include globals.h will know that all your global variables exist, but you won''t be redeclaring them all over the place.

Share this post


Link to post
Share on other sites
Only slightly related. When I feel the urge to use globals I only use one global. That is a pointer to the class or structure containing my globals. It makes it clear when you use the global that this is a global variable, i.e. pGlobals->hFileIn.

Share this post


Link to post
Share on other sites

  • Advertisement