The GNU Debugger
Although make automates the process of building a Linux program, that part of programming is the least of your worries when a program doesn’t work correctly or when a program suddenly quits with an error message. You need a debugger to find the cause of program errors. Linux includes gdb — the versatile GNU debugger with a command-line interface.
Like any debugger, gdb lets you perform typical debugging tasks, such as the following:
Set a breakpoint so that the program stops at a specified line.
Watch the values of variables in the program.
Step through the program one line at a time.
Change variables in an attempt to correct errors.
The gdb debugger can debug C and C++ programs.
Preparing to debug a program
If you want to debug a program by using gdb, you have to ensure that the compiler generates and places debugging information in the executable.
The debugging information contains the names of variables in your program and the mapping of addresses in the executable file to lines of code in the source file. gdb needs this information to perform its functions, such as stopping after executing a specified line of source code.
To make sure that the executable is properly prepared for debugging, use the -g option with GCC. You can do this task by defining the variable CFLAGS in the makefile as
The most common way to debug a program is to run gdb by using the following command:
progname is the name of the program’s executable file. After progname runs, gdb displays the following message and prompts you for a command:
GNU gdb (GDB) 22.214.171.12430417-cvs-ubuntu Copyright (c) 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later ___<http://gnu.org/licenses/gpl.html> This is free software: you are free to change it and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "i686--linux-gnu". For bug reporting instructions, please see: http://www.gnu.org/software/gdb/bugs/. (gdb)
You can type gdb commands at the (gdb) prompt. One useful command, help, displays a list of commands, as the next listing shows:
(gdb) help List of classes of commands: aliases -- Aliases of other commands breakpoints -- Making program stop at certain points data -- Examining data files -- Specifying and examining files internals -- Maintenance commands obscure -- Obscure features running -- Running the program stack -- Examining the stack status -- Status inquiries support -- Support facilities tracepoints -- Tracing of program execution without stopping the program user-defined -- User-defined commands Type "help" followed by a class name for a list of commands in that class. Type "help all" for the list of all commands. Type "help" followed by command name for full documentation. Command name abbreviations are allowed if unambiguous. (gdb)
To quit gdb, type q and then press Enter.