Simple way to manage global variables in c or cpp

January 14, 2019, at 01:49 PM by mgarcia in 2019, Blog, GameDev (1 comments)

Title: Simple way to manage global variables in c or cpp Author: mgarcia Date: 2019-01-14 13:49 +1100 Tags: 2019, Blog, GameDev Comments: Open

1 comments on "Simple way to manage global variables in c or cpp"

  • mgarcia: 2019-01-14 13:49 +1100
    A quick post...

    Yes I use globals where necessary, and no, I'm not ashamed to admit it!

    So this is how I handle global definitions and their instantiation.

    I have many header files where I define global variables, they are prefixed with INSTANCE.
    Before that I have a simple #ifdef checking if a precompiler define exist, INSTANCE_VARS_HERE.

    // global variables defined in a header file like this
    #ifdef INSTANCE_VARS_HERE
    #define INSTANCE
    #else
    #define INSTANCE extern
    #endif

    INSTANCE int g_counter;



    If the header files are used normally in a .cpp file it will reference all the global variables as external, which is normal.

    But in my globals.cpp file, where I want all my global variables instantiated, I tell the header file to instantiate the variables here by defining the INSTANCE_VARS_HERE prior to including the header.


    // in the c/cpp file where to instance the vars
    #define INSTANCE_VARS_HERE
    #include "include_file1.h"
    #include "include_file2.h"

    This will instantiate all the global variables into a single compiled file, which can be helpful keeping track of heap space and reading the NMAP file.



Comments are open.

No log-in required.

Your name or alias (required):

Your plain text comment (required):


Your entered name and comment will be displayed above this form.
There is no reply notifications or editing of comments.

 Enter value: 1256  




← An IndieWeb Webring πŸ•ΈπŸ’ β†’