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?
Only const on an object definition actually makes it immutable. The main point of using const is not to assist the compiler in optimizations but to protect yourself from mistakes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With