A couple years ago I learned that global variables are bad and should be avoided. But I know they are sometimes unavoidable, at least in an embedded system. What do you think is the most elegant way to work with them?
In my projects I have a file called globals.h
where I define all my global variables:
#ifndef GLOBALS_H
#define GLOBALS_H
extern int16_t gVariable1;
extern int16_t gVariable2;
….
#endif
In my main project file I declare all global variables:
/*
***********************************************************************
* global variables *
***********************************************************************
*/
int16_t gVariable1 = 0;
int16_t gVariable2 = 0;
int16_t main (void)
{
gVariable1 = 6;
// do other stuff
}
And know I include globals.h
in every other file of the project which needs access to a global variable.
That works fine, but is there a more elegant way to handle that?