Home  >  Article  >  Backend Development  >  How to debug C++ programs using GDB?

How to debug C++ programs using GDB?

王林
王林Original
2024-06-04 16:13:01791browse

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

如何使用 GDB 调试 C++ 程序?

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

  1. Install GDB. Ubuntu users can use the following command:

    sudo apt-get install gdb
  2. Compile a C++ program to generate debugging information. Use the following g++ options:

    g++ -g -o program program.cpp

Start GDB

  1. Run GDB and load the program:

    gdb program
  2. Use the following command to Attach to the running program:

    attach pid

Basic debugging commands

  • run Run the program
  • break Set breakpoint
  • next Execute the next line of code
  • step Execute the code line by line
  • print Print the value of the variable
  • bt View the call stack
  • quit Exit GDB

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

  1. Compile the program and generate debugging information:

    g++ -g -o program program.cpp
  2. Start GDB and load the program:

    gdb program
  3. Set a breakpoint:

    break 11
  4. Run the program:

    run
  5. The program will stop at line 11:

  6. int c = a + b;

  7. Check the value of the variable:

    print c
  8. One by one Line execution code:

    next
  9. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Related articles

See more