Creating the Debug build

For an executable to be debugged using gdb it has to be compiled a bit differently. This is required because the debugger requires debug information. This debug information mainly comprises of symbol table (i.e. the names of the functions and variables) and file information (to map the machine code of executables onto the source code).

Compilation of programs for GDB

GCC provides the -g flag for compiling the program with debug information present in the executable.

$ gcc -g hello_world.c -o hello_world

The above would compile hello_world.c generating the executable hello_world containing the debug information inside the executable.

Avoid the Optimisation flag

GCC (and almost all other compilers) provide the option of optimisation. The compiler can optimise the high level source code e.g. it can remove the unused variables, unroll the loops, remove the unreachable code. This means that the machine code and the source does not have one-to-one mapping. GCC provides three levels of optimisation. Depending upon the level of optimisation required the flags -O1, -O2 or -03 can be used with gcc. So if you have compiled the program with both optimisation flag and debug flag enabled and try to debug the program in gdb you might get some surprises such as the flow of the program jumps back, the value of the variables are different than initialised or the program flow is not as expected. 

Therefore it is possible to debug an compiler optimised code but it is not advised to use both -g and -O flag together, as you might end up in chasing a problem which is not there.


<< GDB Tutorial Index Creating Release Build >>