Blog /
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
β
An IndieWeb Webring πΈπ
β
2 comments on "Simple way to manage global variables in c or cpp"
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.
#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