Debugging Optimized Code
During optimization, the compiler repositions and reorganizes instructions derived from your source code, resulting in more efficient execution of the program. Because the information in the optimized code has been rearranged, the debugger cannot always identify the source code that corresponds to a set of instructions. For this reason, it is advisable to debug your code before optimizing it whenever possible. You can enable optimization after you finish debugging.
Following are instructions for preventing optimization and suggestions for debugging optimized code, if necessary.
To prevent the compiler from optimizing code
When you create a new project, select the Win32 Debug target. Build and debug the Win32 Debug target until you are ready to build a Win32 Release target. The compiler does not optimize the Win32 Debug target.
– or –
Use the /Od compiler option on the command line, and remove any other /O? compiler options.
– or –
From the Project menu, click Settings.
The Project Settings dialog box appears.
Select the C/C++ tab.
In the Optimizations drop-down list box, select Disable (Debug).
You can enable optimizations after you finish debugging.
Debugging optimized code
Some bugs affect optimized code but do not affect unoptimized code. If you must debug optimized code, use the following techniques:
Use the /Zi compiler option to get maximum symbolic information for your program.
Use the and Registers windows. Set breakpoints at the appropriate locations using the Disassembly window.
To see why the Disassembly window is useful, consider the following example:
for (x=0; x<10; x++)
Suppose you set a breakpoint at this line. You might expect the breakpoint to be hit 10 times. But if this code is optimized, the breakpoint is hit only once, because the compiler recognizes that the first instruction associated with this line, which assigns the value of 0 to x
, needs to execute only once. The compiler moves this instruction out of the loop. If you set a breakpoint on this source-code line, the debugger sets the breakpoint on the first instruction, which executes only once.
The instructions that compare and increment x
remain inside the loop. To set a breakpoint on these instructions, use the . By viewing the object code the source-code line creates, you can set a breakpoint at the appropriate instruction. You can set a breakpoint at the location where the condition is checked or the variable is incremented. You can use the Step Into or Step Over commands in the Disassembly window to step by assembly instructions, which allows greater control than stepping by source-code line.