Preparing to debug

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:

  • 0: This produces no debug information at all and is equivalent to omitting the -g or -ggdb switch
  • 1: This produces little information but which includes function names and external variables which is enough to generate a back trace
  • 2: This is the default and includes information about local variables and line numbers so that you can do source level debugging and a single step through the code
  • 3: This includes extra information which, among other things, means that GDB handles macro expansions correctly

In 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.35.72