Debugging C or FORTRAN Programs with gdb
Some of our FORTRAN users needed a source code debugger, allowing them to step through their code, examine variables, etc. The following documentation on the GNU debugger should be a working introduction.
Compiling Programs with Debugging Symbols Included
You need to modify your gcc or g77 compile command to include
the -g option. So, an example C program compile would be:
gcc -o myprogram -g myprogram.c
An example FORTRAN program compile would be:
g77 -o myprogram -g myprogram.f
Starting gdb
At the shell prompt, type gdb myprogram, where myprogram is
the name of your C or FORTRAN executable. You should see several introductory lines of text including the gdb version number, and then a (gdb) prompt.
Setting a Breakpoint
The most common task in a debugger is to run your program as normal, until you get up to a predefined subroutine or section of code you want to examine in greater detail.
Setting a breakpoint at the top of your main program, in C:
break main
Setting a breakpoint at the top of your main program, in FORTRAN:
break main__
Setting a breakpoint at a particular line number in a particular file:
break myprogram.f:mylinenumber
where myprogram.f and mylinenumber are the source file
and line number where you want to set the breakpoint.
Clearing Breakpoints
To remove an existing breakpoint:
clear myprogram.f:mylinenumber
Stepping
To step through the next line of code, but skip over any detailed examination of subroutines:
next
To step through the next line of code, and also step through any subroutines line-by-line:
step
Examining variable values
To examine the value of an available variable at the current line of the program:
print myvariable
where myvariable is the variable name you want to examine
Resuming Normal Program Execution
To step through all lines of code up to the next breakpoint, if any:
continue
Exiting
To exit gdb:
quit
(Thanks to Barath Baburao for helping test out gdb.)
