You need to compile the code you want to debug with debug symbols. GCC offers two options for this: -g
and -ggdb
. The latter adds debug information that is specific to GDB, whereas the former generates information in an appropriate format for whichever target operating system you are using, making it the more portable option. In our particular case, the target operating system is always Linux and it makes little difference whether you use -g
or -ggdb
. Of more interest is the fact that both options allow you to specify the level of debug information, from 0 to 3:
-g
or -ggdb
switchIn most cases, -g
suffices but reserve -g3
or -ggdb3
if you are having problems stepping through code, especially if it contains macros.
The next issue to consider is the level of code optimization. Compiler optimization tends to destroy the relationship between lines of source code and machine code, which makes stepping through the source unpredictable. If you experience problems like this you will most likely need to compile without optimization, leaving out the -O
compile switch, or at least reduce it to level 1, using the compile switch -O1
.
A related issue is that of stack frame pointers, which are needed by GDB to generate a back trace of function calls up to the current one. On some architectures, GCC will not generate stack frame pointers with higher levels of optimization (-O2
). If you find yourself in the situation that you really have to compile with -O2
but still want back traces, you can override the default behavior with -fno-omit-frame-pointer
. Also look out for code that has been hand optimized to leave out frame pointers through the addition of -fomit-frame-pointer
: you may want to temporarily remove them.