I am a junior embedded software, and I spend most of my time writing C code for dspic33 microcontrollers.
My embedded code is timer interrupts based, with a couple of global variables. Let's consider the simplest code possible:
typedef struct data_t
{
uint16_t a;
uint16_t b;
} data;
data my_data = {0, 0};
int16_t main(void)
{
my_data.a = 10;
while(1)
{
// can access and modify my_data here
}
}
and from another file:
extern my_data data;
void timer_interrupt()
{
if (my_data.a == 10)
{
// stuff here
}
}
This code works fine, but if I add scope control on my_data
by replacing the variable declaration by:
static data my_data = {10, 10};
my_data
is not accessible outside the main file anymore. So cool, I can create a global pointer and continue to access my_data
member anywhere:
static data my_data = {10, 10};
data * const my_data_ptr = &my_data;
// from another file
extern data * const my_data;
void timer_interrupt()
{
if (my_data_ptr->a == 10)
{
// do stuff here
}
}
I prevent eventual reassignment by making the pointer constant, and I am sure my_data_ptr
will point to the my_data
's address for the entire program lifetime. So far, I meet all the requirements - my personal good practice requirements - I limit the scope of my global variables and preserve the variables' integrity.
Now let's imagine two functions, with requirements I define that function one needs read-only my_data
and function two needs a read and write on my_data
, something like:
// read-only access
void function_one()
{
const data * const local_my_data_copy = my_data_ptr;
if (local_my_data_copy->a == 10)
{
// do stuff here
}
}
// read and write access
void function_two()
{
data * local_my_data_copy = my_data_ptr;
if (local_my_data_copy->a == 0)
{
// do stuff here
local_my_data_copy->a = 20;
}
}
So finally, my question is it relevant to create a local copy of my_data_ptr
in every function that needs to access/modify the pointed data? From my perspective, it is relevant for variables access control and can prevent mistakes during code writing. This implementation requests more stack and data space usage because of the extra variables declaration needed, and microcontrollers are memory limited. Hard for me to determine the CPU cost of this implementation. Please let me know your point of view on this piece of code.