Debugging in C++ with GDB
Introduction
Common Types of Bugs
- Syntax Errors: Mistakes in the code that prevent it from compiling.
- Logical (Semantic) Errors: The program runs but produces incorrect results.
What is Debugging?
- The process of finding and fixing errors (bugs) in a program.
- Can involve various techniques, including print statements, code reviews, and using debugging tools.
Why Debug with Debuggers?
- Even the best programmers make mistakes.
- Debugging is an essential skill for every programmer.
- Learning to use a debugger effectively can save you hours of frustration.
Debugging Approaches
- Print statements (
std::cout). - Code reviews and pair programming.
- Debugging tools like GDB.
Debugging with GDB
What is GDB?
GDB stands for GNU Project Debugger and was first written in 1986.
A debugging tool for C++ (and other languages).
Lets you step through the code one instruction at a time to see what is happening.
Loads executable files that were compiled with debug information (
-g).
Compiling a Program for Debugging
g++ -g <source> -o <executable>
Launching and Exiting GDB
gdbStart GDB.gdb <program>Start GDB.gdb --argsStart GDB and pass arguments to executable.quitExit GDB.
Run a Program to be Debugged
runRun the executable that was previously set.fileSet the executable to run.
Breakpoints
break <where>Set a new breakpoint.enable <breakpoint#>Enable a disabled breakpointdisable <breakpoint#>Disable a breakpoint.delete <breakpoint#>Remove a breakpoint.clearDelete all breakpoints.
Stepping through Lines of Code
stepGo to next instruction (source line), diving into function calls.nextGo to next instruction (source line) in this function.continueContinue execution until the next breakpoint.finishContinue until the current function returns.
Variables and Memory
printPrint content of variable/memory location.displayLikeprintbut shows the information with each step.undisplayRemove thedisplaywith the given number.info localsPrint the local variables or arguments in the current stack frame.
GDB in VSCodium or VS Code
Prerequisites
Install the C/C++ Debug (gdb) extension.
If running in WSL, install the Open Remote - WSL extension.
- Ensure that the C/C++ Debug (gdb) extension is installed within WSL.
Open the lab/project folder (not just a source file or the whole repository).
- If using WSL, make sure to connect to WSL (remote connection).
Open a C++ file.
Project Setup
Open a C++ File in the Folder.
Click on the “Run” menu at the top.
Click on the “Add Configuration” menu item and select “G++ (GDB/LLDB)”.
Click “Add Configuration” on the bottom right.
Select “C/C++: (gdb) Launch”.
Modify the “name”, “program”, “args”, and “cwd” fields as desired.
https://code.visualstudio.com/docs/cpp/launch-json-reference
Use .gitignore files
There are often files you do not want to share (executable, debug configuration).
Git will not track files and folders specified in a .gitignore file.
.vscode/*
obj/*
main
test-runner