How do I debug with gdb/lldb in C++?

Debugging C++ applications can be effectively done using tools like GDB (GNU Debugger) and LLDB. These tools allow developers to inspect the state of a program during its execution, set breakpoints, and step through code to identify and fix bugs.

Using GDB

To debug your C++ program with GDB, follow these steps:

  1. Compile your code with debugging information using the `-g` flag:
  2. g++ -g -o my_program my_program.cpp
  3. Start GDB with your executable:
  4. gdb my_program
  5. Set breakpoints in your code:
  6. (gdb) break main
  7. Run the program:
  8. (gdb) run
  9. Use commands like `next`, `step`, `print` to navigate through your code and inspect variables.

Using LLDB

LLDB works similarly to GDB. Follow these steps to use LLDB:

  1. Compile your C++ program with debugging symbols:
  2. clang++ -g -o my_program my_program.cpp
  3. Launch LLDB with your executable:
  4. lldb my_program
  5. Set breakpoints:
  6. (lldb) breakpoint set --name main
  7. Run the application:
  8. (lldb) run
  9. Use commands like `next`, `step`, `print` to navigate and inspect the state of your program.

debugging GDB LLDB C++ breakpoints inspect variables