I am new in this field. Previously I was doing microcontroller programming where I used volatile variables to avoid compiler optimization. But I never saw such volatile declarat
If you are using gcc
for compilation then add/modify CFLAGS
-O2
or -O3
to enable a bunch of generic performance optimisations.
Os
to enable code size optimisations.
A long list of flags that control individual gcc compiler optimisation options is available here.
Most often volatile
is used NOT for optimising the code, but to ensure validity of data.
The declaration of a variable as volatile
tells the compiler that the variable can be modified at any time externally to the implementation by
As the value of a volatile-qualified variable can change at any time, the actual variable must always be accessed whenever the variable is referenced in code.
This means the compiler cannot perform optimizations on the variable. Marking a variable volatile
forces the compiler to generate code that ignores the variable in the CPU register and actually reads the underlying memory/hardware-register mapped at the address referred-to by the variable.
Also checkout the various aspects of using volatile along-with compiler optimisations.