Is a C compiler obligated to always reload const value from memory?

1.7k views Asked by At

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?

2

There are 2 answers

25
Jongware On

If marked as volatile the 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 const and 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 .data section 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.

3
n. m. could be an AI On

It looks like your variable is really a constant (i.e. doesn't change during program execution) with a value unknown to the compiler. If this is the case, you can declare it like this:

extern const int variable;

(i.e. without volatile and without an initializer) and let the linker script or other tools set up the correct value.

The compiler will then be permitted to load it and potentially leave it in a register forever, but not replace it by 0 or any other value at compile time.