gdb is the "GNU" debugger. It is used to find errors in programs that compile correctly but either crash (halt with an error such as "segmentation violation" or "bus error") or produce incorrect results when run. Gdb allows you to start and stop your program at any point and view the current values of the program variables. If a program crashes, then gdb can be used to determine the statement that caused the crash and display the values that the program variables had when the crash cocurred.
Gdb cannot be used for programs that do not compile without errors. Such "Compilation errors" can be difficult to resolve at first, but ultimately they are the easiest errors to track down and fix. Compilation errors occur when the compiler encounters C code that is syntactically incorrect. The most common such errors are missing or extra parentheses/brackets/semicolons, misspelled words, improperly declared functions and functions called with incorrect or the wrong number of arguments.
In general, even one simple syntax error will produce numerous, often incomprehensible, error messages. The key to fixing the errors is to mostly ignore the error messages except to locate the first line where an error was found. The corresponding error message may or may not provide additional useful information, but it is almost certain that the first syntax error in your program occurs around that line. Once you fix that error you can repeat the above process to find the next error.
In order to use gdb to debug a program, the program first needs to be compiled using the "-g" option. For example, if the executable "hello" whose source is in "hello.c" is normally compiled using a command like
gcc hello.c -o helloThen it should be compiled instead with the command
gcc -g hello.c -o hello
This will compile "hello" with symbolic information needed by gdb. Note: Most compilation options work fine in conjunction with the "-g" option, but it is best not to use optimization flags such as "-O" or "-O3" when compiling with the "-g" option.
For reference, here is a summary of the most useful gdb commands, most of which are explained in more detail in the examples. You can also click here to obtain a nice two-page reference sheet that describes all of the gdb commands.
To debug the executable "hello", begin by typing
gdb helloThese are among the more useful gdb commands: