Search code examples
cembeddedinterruptvolatile

C: Using static volatile with "getter" function and interruptions


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?


Solution

  • A getter function doesn't help in any way here over using volatile.

    • Assume the compiler sees you've just fetched the value two lines above and not changed it since then.
    • If it's a good optimizing compiler, I would expect it to see the function call has no side effect simply optimize out the function call.

    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.