Debugging Optimized Code

Debugging C/C++ works best with the code that has not been optimized. Turning on even the minimal optimization level (-O1) can introduce various debugging glitches:

  • Breakpoints not setting in some locations
  • Stepping through functions could appear sporadic, jumping up and down
  • Some variable values could be completely missing

To avoid this, C/C++ projects usually come with two configurations: Debug with optimization disabled (-O0) and Release with optimizations enabled (-O3 or –Os).

If this layout does not work due to some reason, you can try the workarounds described below.

Updating GCC version

Newer versions of GCC and GDB tend to handle it slightly better, so updating it could help. It will still be far from perfect though.

Selectively disabling optimization for individual files

If you are using MSBuild, you can override the optimization level of individual files by opening MSBuild project properties for the particular files, and changing the optimization level: