Was just wondering the reasoning behind cliffs FAQ#4 "if using avr-gcc avoid -O0 optimization at all costs"
Because -O0 is not minimal optimisation. It is more like deliberate inefficiency.
Not only will it make code larger and SLOWER but it will make the hardware timed sequences fail. e.g. CLKPR, JTD, EEPROM, ...
Yes, some of these sequences are handled by header files e.g. < avr/power.h>
Most compilers will produce acceptable code when you specify no optimisation. GCC will just produce bad code.
In practice -O1 or -Od should make debugging easy and still have reasonable code (that works).
-O is a test mode for the compiler developers to study the output of the code generator when it's output is not then subject to optimisation. No "normal" end user should ever use it.
If you want "mininmal" optimisation always use at least -O1. If it's just a question of watching a variable in a debugger then consider making just that one item "volatile" which is almost the same as making accesses to it behave like -O0.
There are many things you may do with an AVR (like turning off JTAG using JTD, unlocking features on Xmega using CCP, changing the clock speed using CLKPR, etc. etc) that can usually be written in C but NONE of these things will work if you then build the code -O0 as it won't meet the 4 cycle timing requirement as the generated code is unbelievably slow and bloated (speed and size that is then improved by optimisation).
One of the reasons for choosing avr-gcc in the first place is that it has a very aggressive optimiser. It would seem a bit pointless to pick a heavily optimising compiler for your AVR work then turn that optimiser off!
Unfortunately people at Atmel did not initially understand about -O0 and in early days/versions they drove the GCC compiler from Studio by passing -O0 for the "Debug" builds - it was a BIG mistake! (I alerted them and they later corrected it).
By the way, I don't know if it's yet in any compiler version issued by Atmel but GCC now has or soon will have (for AVR) a new optimisation level called -Og (the g here matches -g which means "embed debugging info"). The idea of this optimisation level is it generates code that is "easy" to debug. It could well be a better option than -O1 for "Debug" builds when it becomes mainstream.
© 2020 Microchip Technology Inc.