If you need to debug a C or C++ program on Linux, I’d normally recommend using ddd, or some other graphical source code debugger. But if you are debugging remotely (over ssh for example), it’s worth knowing the basics of the GNU Debugger (gdb), a interactive command line tool that can be used over an ssh connection.
To make sure that gdb can debug your programs, you need to specify the -g option on the gcc command line. This will add debugging information to the object files and executable.
To run a program under gdb, run:
gdb program
To debug a core dumped by a crashed program using gdb, run:
gdb program core
Here’s a quick summary of some useful commands:
Command | Purpose -----------------------+---------------------------------------- break function | set a breakpoint on a function run [arg ...] | run [with args] to the first breakpoint bt [full] | display the stack [and locals] f #|up|down | select a stack frame n | step to the next line s | step into a function call finish | run to the end of the function p variable | print a variable p pointer->member | print a member (or any expression) p variable=expression | set a variable to the result of an expression c | continue from a breakpoint quit | quit qdb shell command | run a command cd directory | change to directory pwd | print the working directory info threads | list the threads thread thread-id | switch to a thread skip function function | mark a function as never to be stepped into
Pingback: Debugging a Core with DDD – Programming with Jim