I have a const variable in my embedded C program. It's defined and initialized with 0 in program code. It's placed in a special ROM area via linker script. One can change the content of the special area via special programming procedure, but it cannot be changed during main program execution.
The question is whether I have to declare the constant as volatile. If it's not marked as volatile, is the compiler allowed to replace all references to it with 0? Or is it obligated to load it at least once during program execution?
If marked as
volatilethe compiler is obliged to load it from memory every time it needs it value.If not marked as
volatile, the compiler may load it once from memory, store it in a register, and use this register instead of loading it again.A not-optimizing compiler may do this - but it also may, stupidly, load it every time. (As not reloading is in fact an optimization in itself.)
Optimizing compilers may notice the
constand decide it can be compiled with its real, literal value; up to a point where the original constant does not appear at all in the.datasection of your program. (Or maybe it does but it never gets "read".)Since you change the value in a linker script, the compiler cannot "know" the value got changed after compiling. In that case, use
volatile: the only way to tell the compiler not to trust that the value is known when compiling.