Search code examples
cgccembeddedc99volatile

Are global variables refreshed between function calls?


Im writing embedded firmware, and find it sometimes hard to decide when I need volatile or not.

When I have a function that waits for some boolean flag to be changed by an interrupt, it's obvious that the flag needs to be volatile, because else the function would wait forever, since the compiler doesn't realise the value can be changed by the interrupt.

But when I have a short function that just checks a flag in the first line, I would expect the flag doesnt need to be volatile, because its value will be read every time I enter the function? So when an interrupt modifies its value between the first time I call the function, and the second time, I will get the fresh value. Or is it not guaranteed that every time I enter the function all caching registers are cleared?


Solution

  • You would still need to mark your variable volatile: since the optimizer is free to inline your functions, especially the short ones, calling your function in a loop without a volatile mark for accessing hardware-modified memory would place you in danger of not reading the memory after the initial iteration.