Debugging Optimized Code in Visual Studio 11
Join the DZone community and get the full member experience.Join For Free
executive summary: when using the windows debugger engine to debug optimized c++ code compiled with visual studio 11 you can step into inline functions and see local variables that are stored in cpu registers.
the current (visual studio 2010 compiler) state of affairs is that compiler optimizations are way smarter than the debugger engine, which lacks the information necessary to map a fully optimized binary back to the source code in a reliable manner. this is why c++ developers don’t like debugging optimized code: as if the compiler-introduced reorderings which take you from one line to a completely unrelated line at a whim aren’t enough, you often don’t see all local variables because they are stored in cpu registers at runtime, and you can’t step into or set breakpoints in functions that have been inlined.
the visual studio 11 c++ compiler helps by emitting additional debug information in the pdb. this information allows the debugger to map more accurately the optimized assembly stream back to the source. currently, to get this to work, you need the visual studio 11 c++ compiler to build your code and you need to use the most recent debugging tools for windows build – it contains the windows debugger you must then use to work with this information * . fortunately, you can use the windows debugger engine to debug c++ code without leaving visual studio 11 – which means it ain’t all that bad.
the magic ensues when you add the /d2zi+ undocumented compiler flag to your c++ compiler settings. (obviously, this is something that will change before the release.) when you launch your program with windbg, or use the windows debugger engine in visual studio to debug your code, you will see local variables and will be able to step into inline functions:
finally, this also means that the debugger will be able to show inline functions on a call stack. for example, if you encounter an exception in an inline function and store a crash dump of the problem, you’ll have the debugger point at the inline function as the source of the crash. in windbg, a call stack would look similar to the following, complete with line numbers:
(inline) -------- vanillac__consoleapp!addtwonumbers+0x9 [d:\...\vanillac++consoleapp.cpp @ 9]
0035fae4 00901267 vanillac__consoleapp!wmain+0x39 [d:\...\vanillac++consoleapp.cpp @ 25]
0035fb24 75f7339a vanillac__consoleapp!__tmaincrtstartup+0xfd
0035fb30 77049ed2 kernel32!basethreadinitthunk+0xe
0035fb70 77049ea5 ntdll!__rtluserthreadstart+0x70
0035fb88 00000000 ntdll!_rtluserthreadstart+0x1b
* here’s to hoping that in the very near future we’ll see this supported by the built-in c++ debugger in visual studio, and not just the windows debugger.
Published at DZone with permission of Sasha Goldshtein, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.