in my (personal) embedded project global variables are piling up. I need those variables to be acessible from the ISR (interrupt service routine) and/or from a menu system (so that they can be modified by the user) but at the same time I'd like to avoid having too many globals.
Since they can be grouped for modules I thought that I can encapsulate them in their own .c file, declared as static
or static volatile
, and expose to the outside world some functions to handle them.
Something along the line of:
in module1.c
#include module1.h
static volatile int module1_variable;
int getModule1Var(void){
return module1_variable;
}
void setModule1Var(int i){
//some code to disable interrupts for atomic operations
module1_variable = i;
//some other code to re-enable interrupts
return;
}
module1.h would contain the function prototypes, structs and all the other elements for making the module work except for the static variable definition of course
in main.c
#include module1.h
void main(){
//setting the variable value, could be done from a menu
setModule1Var(15);
//remaining application code
}
void generic_ISR(){
//trivial usage example
doSomething(getModule1Var());
return;
}
This scheme would naturally be extended to the other modules.
Now my questions are:
is this a good approach? Is it the same to simply have a bunch of globals? Any major drawbacks?
I also thought I could use some sort of mix like still having the global variables to allow direct manipulation by the ISR (since function calls from the ISR are sometimes frown upon) and the functions in every other case. Would this be better?