Saturday, April 10, 2010

Debugging Tools - Unix gdb

Main gdb Commands

Before you start, compile the program using the -g option, i.e.

cc -g sourcefile.c

Then to start gdb type

gdb filename
where `filename' is the executable file.

The q (Quit) Command: Quits gdb.

The r (Run) Command: This begins execution program.

The l (List) Command: Use this to list parts of your source file(s). E.g. typing
l 52
will result in display of Line 52 and the few lines following it.

The b (Breakpoint) and c (Continue) Commands: This pause the execution of the program at the specified line. For example,
b 30
stop program every time the program gets to Line 30.

If there is more than one source file, precede the line number by the file name.
To continue executing the program, type c (for the continue command).

One can also use a function name to specify breakpoint. For example,
b main
stop at the first line of the main program.

The d (Display) and p (Print) Commands: This prints value of the indicated variable or expression when the program pauses. E.g.
disp NC
print the value of the variable NC every time the program pauses.
To cancel a display command use the undisplay command.
A related command is p; which prints value of the variable just once.

The printf Command: This is similar to printf in C. E.g., to print two integer variables, X and Y, give gdb the command:
printf "X = %d, Y = %d\n",X,Y

The n (Next) and s (Step) Commands: Execute the next line of the program, and then pause again. If that line happens to be a function call, then n and s will give different results. If you use s, then the next pause will be at the first line of the function; if you use n, then the next pause will be at the line following the function call (the function will be single-step executed, but there will be no pauses within it).

The bt (Backtrace) Command: In case of an execution error with a mysterious message like ``bus error'' or ``segmentation fault,'' the bt command will tell you where in your program this occurred, and if in a function, where the function was called from.

The set Command: Change the value of a program variable. For example, to change value of int variable x in your program, use
set variable x = 12
which will change x's value to 12.

The call Command: Calls a function in your program during execution. E.g.,
call x()

The define Command: Put together one or more commands into a macro. For instance, recall our example from above,
printf "X = %d, Y = %d\n",X,Y

To frequently use this command during your debugging session, you could do:
define pxy
Type commands for definition of "pxy".
End with a line saying just "end".
>printf "%X = %d, Y = %d\n",X,Y
>end

Then you could invoke it just by typing ``pxy''.

The kill (Kill) command:
Stops the program without quitting gdb
kill

You can also use GUI-based interface for a better view of gdb. One of them is
ddd

No comments:

Post a Comment