Simple way to manage global variables in c or cpp
January 14, 2019, at 01:49 PM (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
#define INSTANCE extern
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
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.