Simple way to manage global variables in c or cpp

January 14, 2019, at 03:49 AM by mgarcia in 2019, Blog, GameDev (2 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

2 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.

  • mgarcia: 2019-03-03 12:48 +1100
    Adding to above, I came across this:

    #pragma once

    #ifdef __MAIN__
    #define __EXTERN(type, name, value) type name = value
    #else
    #define __EXTERN(type, name, value) extern type name;
    #endif

    and then declare your variables in that same header file, like such:

    __EXTERN(volatile int, MyVolatileInteger, 0);


    Which is pretty cool also, posted here:
    https://stackoverflow.com/questions/2544852/using-the-same-variable-across-multiple-files-in-c



Comments are open.


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: 6982  



RSS Feed @mgarcia_org Twitter Feeder my random Youtube videos
← An IndieWeb Webring πŸ•ΈπŸ’ β†’



Page last modified on March 04, 2019, at 02:48 AM and visited 3912 times.

Powered by PmWiki