Search code examples
cmemoryvolatile

Volatile is not preventing a variable from being optimized


As I know, "volatile" keyword is used to prevent compiler to optimize an unused variable. I am working with an STM32 board and I declare and initialise a variable as follows;

volatile uint32_t errorCallbackCounter = 24 ;

And never use it again.

While debugging, this variable is not seen. I am checking it with STMStudio( a real time variable watcher ) and when I want to import variables, the adress of errorCallbackCounter is seen as 0x0.

But when I use it in anywhere, it becomes visible.

So volatile keyword is not doing its job or -more probably- I know something wrong about it.

Thanks in advance.


Solution

  • Variables that are never used can be dropped by the linker

    The volatile keyword affects the code that accesses the variable, preventing the access from being rearranged or dropped by the compiler. The line above is a variable definition with an initializer, that doesn't count as an access, it gets arranged before main() starts. But if it isn't referenced by accessible program code, isn't accessed at all, the linker thinks that it's safe to remove it, no one would notice.

    You can however mark the variable as "it's needed no matter what" with

    __attribute__((used))
    

    placed at the end of the definition. This works with gcc, other compilers might have another directive for it. There is also a linker option that I can't recall right now to include all unused data sections in the executable.