Navigation menu:

Latest news:

Mar 22nd, 2013:
Updated the MayaFPS plug-in to version 1.1.0. The update allows the user to select which mouse button will engage first person controls (RMB/XButton1/XButton2). Suggested by JO.

Search:


XML: RSS Feed XML: Atom Feed

Category list:

Tag Cloud:

Archives

If you decide that you want to use global variables, you may find yourself needing to declare those globals in a header file and defining (and initializing) them in a cpp file. As the list of globals grows longer, the inconvenience of keeping the declaration list and definition list in sync grows.

We can tidy things up by using the preprocessor (and placing the globals in a namespace, but that's irrelevant). An example of a typical list of global variables that is declared in a header and defined in a cpp is this:

/*in header (hopefully an internal header and not an API header)*/
namespace Globals
{
extern bool bOptionsLoaded;
extern std::vector< Option* > options;
};

/*in .cpp*/
# include "Header.h"
namepsace Globals
{
bool bOptionsLoaded = false;
std::vector< Option* > options;
};

We can use the preprocessor by defining two macros: GLOBALVAR, and GLOBALVAR_INIT. Using these, the code above becomes like this:

/*in header*/
namespace Globals
{
    GLOBALVAR_INIT( bool, bOptionsLoaded, false );
    GLOBALVAR( std::vector, options ); // not _INIT because no initialization value is assigned.
};

/*in cpp*/
# define GLOBALVAR_DEFINE
# include "Header.h"
# undef GLOBALVAR_DEFINE

Now the list is kept in one single place (the header file), and many files can include that header, but exactly one cpp file is required to #define GLOBALVAR_DEFINE before including the header in order for the variables to be defined, or else you get "unresolved external symbol" errors, or "symbol already defined in *.obj" errors.

Here is the code for the macros:

# ifndef GLOBALVAR
# define GLOBALVAR_DECL( type, name )                   extern type name
# define GLOBALVAR_DEF( type, name )                    type name
# define GLOBALVAR_DEF_INIT( type, name, value )        type name = value
# ifdef GLOBALVAR_DEFINE
# define GLOBALVAR                            GLOBALVAR_DEF
# define GLOBALVAR_INIT                       GLOBALVAR_DEF_INIT
# else
# define GLOBALVAR                            GLOBALVAR_DECL
# define GLOBALVAR_INIT(type,name,val)        GLOBALVAR_DECL(type,name)
# endif
# endif

It's an old approach it seems. Now you can overuse globals all you want without the hassle of matching the definitions with the declarations!

| Used tags: ,