muyustan
muyustan

Reputation: 1585

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.

Upvotes: 1

Views: 649

Answers (2)

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.

Upvotes: 2

theSealion
theSealion

Reputation: 1102

volatile means the system will load this variable from memory each time it is accessed. The compiler is not allowed to store the data directly into an register.

The volatile keyword prevents the compiler from performing optimization on code involving volatile objects, thus ensuring that each volatile variable assignment and read has a corresponding memory access. Without the volatile keyword, the compiler knows a variable does not need to be reread from memory at each use, because there should not be any writes to its memory location from any other thread or process.

Upvotes: 2

Related Questions