If you are using gcc for compilation then add/modify CFLAGS
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
- the operating system
- another thread of execution
-- interrupt routine
-- signal handler
- underlying hardware
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.