Electronic – Is it really a good-practice disable optimizations during the development and debugging phases

best practicebooksmicrocontrolleroptimizationpic

I've read Programming 16-Bit PIC Microcontrollers in C, and there is this affirmation in the book:

During the development and debugging
phases of a project, though, it is
always good practice to disable all
optimizations as they might modify the
structure of the code being analyzed
and render single-stepping and
breakpoint placement problematic.

I confess I was a little confused. I didn't understand if the author said that because of the C30 evaluation period or if it's really a good practice.

I'd like to know if you actually use this practice, and why?

Best Answer

This is pretty standard in software engineering as a whole - when you optimize code, the compiler is allowed to re-arrange things pretty much however it wants, as long as you can't tell any difference in operation. So, for instance, if you initialize a variable inside every iteration of a loop, and never change the variable inside the loop, the optimizer is allowed to move that initialization out of the loop, so that you're not wasting time with it.

It might also realize that you compute a number which you then don't do anything with before over-writing. In that case, it might eliminate the useless computation.

The problem with optimization is that you'll want to put a breakpoint on some piece of code, which the optimizer has moved or eliminated. In that case, the debugger can't do what you want (generally, it will put the breakpoint somewhere close). So, to make the generated code more closely resemble what you wrote, you turn off optimizations during debug - this insures that the code you want to break on is really there.

You need to be careful with this, however, as depending on your code, optimization can break things! In general code that is broken by a correctly functioning optimizer is really just buggy code that's getting away with something, so you usually want to figure out why the optimizer breaks it.