Do I turn off every optimization flag for debug builds?
Yes, I would say that is the best way to go, and it does really matter! Depending on your code, your understanding of the compiler/debugger and level of optimisation chosen, the experience of debugging it will vary from mildly annoying to frustrating and almost useless. This answer gives a synopsis of the different levels for gcc and this question has several answers going into more detail about optimisations.
As a summary, the compiler is in general allowed to modify your code in any way it sees fit, as long as it still behaves as if all your statements were executed exactly as written. In practice, -O1
already enables dozens of techniques and -O2
and -O3
will probably leave almost nothing untouched, which makes it harder to pinpoint issues because:
- Stepping through code may visit statements in a different order or skip them entirely, also hindering the use of breakpoints;
- Function calls may disappear because they were inlined, and no longer be callable from the debugging prompt;
- Local variables tend to have shorter lifetimes than in your source code, so you can't always query their values.
I personally build with CMake and primarily use two of its build types:
Debug
(-g
): No optimisations, compiles runtime assert
statements;
RelWithDebInfo
(-O2 -g -DNDEBUG
): Fast code without these assertions that is harder to debug, but suitable for performance analysis once your program is working correctly.