Simple way to manage global variables in c or cpp
January 14, 2019, at 03:49 AM (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
#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.
- mgarcia: 2019-03-03 12:48 +1100 Adding to above, I came across this:
#define __EXTERN(type, name, value) type name = value
#define __EXTERN(type, name, value) extern type name;
and then declare your variables in that same header file, like such:
__EXTERN(volatile int, MyVolatileInteger, 0);
Which is pretty cool also, posted here:
Comments are open.