Debugging with optimization on

Thread Starter

Toru Fujinami

Joined Sep 26, 2016
I am writing a firmware on C language. and I have issue with optimization right now.
When I am running my code on optimization level 0 or 1, the code runs perfectly.
When I put higher optimization level (2 or 3), the code stops working.

I want to figure out why this is happening.
But optimization does not let me put break point on certain lines..

In general, how does everyone debug code with Optimization?

Thank you,


Joined Oct 2, 2009
It would help to know what software tools you are using on what processor.
Usually when I am debugging with IAR EW, I turn off optimization. I don't encounter any problem while doing that.


Joined Mar 31, 2012
In general, the debugging capabilities are dependent on the compiler (and/or IDE) you are using.

The problem is likely that something in your code is getting optimized away because the compiler doesn't recognize that you are relying on it being there for some other reason. For example, for() loops that are there to act as a delay element often get optimized away.

You can put in print statements (what I call instrumenting your code) to see what is going on, but those can have the affect of making code that is otherwise getting optimized out stay put. Even then, you can add print statements until the problem goes away and then focus on the part of the code that the presence of a print statement was the magical, mystery bullet.


Joined Jun 26, 2012
+1 Which chip and compiler?
In Microchip C (HiTech and XC8), what you describe is common. The optimizer has figured a way to implement the logic of the program without generating code for the source line in question. Trying to set a breakpoint on a source line fails and stepping through the code seems to take unexpected paths. That's normal, at least in those environments.
One approach to figuring it out is to open the disassembler output and/or Program ROM windows and debug that piece of code in assembler step by step.
Code that runs in non-optimized vs. optimized modes is frequently a timing issue that has been unmasked by the changes in the object code. Entire routines can disappear if the compiler deems they are not needed. Simple counting delays can also go away if the result is not used-depends on the compiler. Sometimes its a compiler bug but not often - check the release notes.

Let us know some info and post your code if you can.

Good luck.


Joined Feb 24, 2006
Can you look at the assembly listing output of the compiler in the neighborhood where you suspect the failure?
Can you give us a list of the optimizations used in levels 2 & 3?

Switch and nested if-else constructs are known to cause problems with some compilers.

Thread Starter

Toru Fujinami

Joined Sep 26, 2016
Thank you everyone for the solutions and details of issues.
I am using Pic24F chip. And MPLAB for IDE.

I will try to debug now with the techniques mentioned here :)