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 xandenable 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). Usec-iter1to skip the first iteration, typecagain 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:xto set a breakpoint at line x of function.c. bt: used to backtrace the path of code execution.btgives 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 xjumps to frame x (f 0jumps 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.
Related Topics¶
- Building C++ Projects with Bazel | C++那些事
- Debugging Bazel Builds with LLDB | C++那些事
- CMake Essentials in Practice | C++那些事
- Getting Started with the Conan C++ Package Manager | C++那些事
- C++ Insights Compile-Time Observation | C++那些事
- Interactive C++ in Jupyter Notebook | C++那些事
- C++ string to int | C++那些事
- The C++ dbg-macro Debugging Macro | C++那些事
- GCC Compilation Flags Explained | C++那些事
- GDB Python Extension Debugging | C++那些事