Suppose I have the following C code:
/* clock.c */
#include "clock.h"
static volatile uint32_t clock_ticks;
uint32_t get_clock_ticks(void)
{
return clock_ticks;
}
void clock_tick(void)
{
clock_ticks++;
}
Now I am calling clock_tick
(i.e.: incrementing clock_ticks
variable) within an interruption, while calling get_clock_ticks()
from the main()
function (i.e.: outside the interruption).
My understanding is that clock_ticks
should be declared as volatile
as otherwise the compiler could optimize its access and make main()
think the value has not changed (while it actually changed from the interruption).
I wonder if using the get_clock_ticks(void)
function there, instead of accessing the variable directly form main()
(i.e.: not declaring it as static
) can actually force the compiler to load the variable from memory even if it was not declared as volatile.
I wonder this as someone told me this could be happening. Is it true? Under which conditions? Should I always use volatile
anyway no matters if I use a "getter" function?
A getter function doesn't help in any way here over using volatile
.
If get_clock_ticks()
would be external
(i.e. in a separate module), matters are different (maybe that's what you remember).
Something that can change its value outside normal program flow (e.g. in an ISR), should always be declared volatile
.