When you use the -O0 compiler flag in C, you tell the compiler to avoid any kind of optimization. When you define a variable as
volatile, you tell the compiler to avoid optimizing that variable. Can we use the two approaches interchangeably? And if so what are the pros and cons? Below are some pros and cons that I can think of. Are there any more?
- Using the -O0 flag is helpful if we have a big code base inside which the variables that should have been declared as
volatile, are not. If the code is showing buggy behavior, instead of going in the code and finding which variables need to be declared as volatile, we can just use the -O0 flag to eliminate the possibility that optimization is causing the problem.
- The -O0 flag will affect the entire code while the
volatilekeyword only affects a specific variable. If we're working on a small microcontroller for example, this could be a problem since using -O0 may produce a big executable.
-O0 is in no way a replacement for proper use of
volatile, because the code that does not work when it is properly optimized by the compiler is inherently broken. You do not want a broken code giving you an appearance of "working" until someone forgets to throw the
It is unusual even for large code bases to have a need for many volatile variables, in terms of the total percentage of variables in the code. Fixing a large code base with missing
volatile is likely to require finding a few strategic places where multiple variables need to be
volatile, and fixing just these few, rather than taking a "shotgun approach" and disabling all optimizations.