Using GDB to debug C++ program involves: setting up GDB, using the -g option to compile the code, generating debugging information, starting GDB and loading the program, debugging using the following commands: run: run the program break: set a breakpoint next: execute the next line of code step: step by step Line execution code print: Print the value of the variable bt: View the call stack quit: Exit GDB
How to use GDB to debug C++ programs
Introduction
GDB (GNU Debugger) is a powerful tool for debugging C++ programs. It allows programmers to inspect the status of a program at runtime, set breakpoints, and execute code line by line.
Set up GDB
Install GDB. Ubuntu users can use the following command:
sudo apt-get install gdb
Compile a C++ program to generate debugging information. Use the following g++ options:
g++ -g -o program program.cpp
Start GDB
Run GDB and load the program:
gdb program
Use the following command to Attach to the running program:
attach pid
Basic debugging commands
Practical case
The following is an example of a simple C++ program, which uses GDB to debug:
#include <iostream> using namespace std; int main() { int a = 10; int b = 20; int c = a + b; cout << "c = " << c << endl; return 0; }
Debugging steps
Compile the program and generate debugging information:
g++ -g -o program program.cpp
Start GDB and load the program:
gdb program
Set a breakpoint:
break 11
Run the program:
run
The program will stop at line 11:
int c = a + b;
Check the value of the variable:
print c
One by one Line execution code:
next
Exit GDB:
quit
Conclusion
GDB is a powerful Tools for debugging C++ programs. By following these steps, you can use GDB effectively to find and fix bugs in your programs.
The above is the detailed content of How to debug C++ programs using GDB?. For more information, please follow other related articles on the PHP Chinese website!