Skip to content

Last updated:2026-10-12

Debugging C++ Programs with GDB

When debugging C code with the GNU Debugger (GDB), you will find that it is the most popular debugger on UNIX systems for debugging C and C++ programs. Here is a concise, easy-to-understand explanation of debugging C code with GDB:

First, switch to the current folder containing your code on the command line and run the following command:

gcc -g -Wall code.c -o output

Here, the -g option is necessary for using the GDB tool. The -Wall option is used to display warning messages. This will create an executable file named "output".

Then, run the following command to open the GDB dialog and load the symbol information from the output file (or simply put, set up the whole environment to debug code.c):

gdb output

The following commands can help you debug:

  • list: lists the source code.
  • b x: sets a breakpoint at x. x can be the name of a module or a line number. For example, x can be a function name such as main.
  • r: runs the program (until a breakpoint) and provides the result; that is, it runs the code up to the breakpoint and produces the result. [With arguments, it is: r arg1 arg2 arg3 ...]
  • info breakpoints x: gives detailed information about breakpoint x.
  • info breakpoints: gives detailed information about all breakpoints.
  • delete x: deletes breakpoint x.
  • disable x and enable x: disable and enable breakpoint x.
  • print p: prints the value of the variable p.
  • display p: displays the value of the variable p after each run (automating the whole process).
  • c: continues executing the program (skipping iterations such as for loops). Use c-iter1 to skip the first iteration, type c again to skip the second iteration, and so on.
  • You can also use extra conditions, such as b x if (y > m), which means: set a breakpoint at line x if the value of y is greater than m.
  • GDB can also set breakpoints across multiple files. For example, if a function defined in function.c is called from program.c, you can use b function.c:x to set a breakpoint at line x of function.c.
  • bt: used to backtrace the path of code execution. bt gives an indexed list showing the frames the code passed through, for example: #0 a description of frame 0, #1 a description of frame 1, and so on, where 0 is the most recent frame.
  • Typing f x jumps to frame x (f 0 jumps to frame 0) and shows the values of the variables when the corresponding function was executing.
  • s: used to step into a function and get more details.
  • next: used to execute the code line by line.

Comments