Overview
gdb provides in-depth debugging capabilities, allowing you to control program execution flow, inspect variable values, and examine memory states. It is particularly useful for analyzing issues in compiled binary files.
Key Features
- Start/stop a running program
- Set breakpoints
- Inspect and modify variable values
- View stack traces
- Examine memory contents
- Analyze core files
Key Options
gdb is primarily used in interactive mode, but you can also use specific options at startup to configure initial settings or run non-interactive scripts.
Startup/Connection Options
Generated command:
Try combining the commands.
Description:
`gdb` Executes the command.
Combine the above options to virtually execute commands with AI.
Usage Examples
Since gdb is often used interactively, the examples include commands entered within the gdb prompt.
Start a Basic Debugging Session
gdb ./my_program
Load a compiled program (e.g., my_program) into gdb to start a debugging session.
Set Breakpoint and Run
gdb ./my_program
(gdb) b main
(gdb) r
Set a breakpoint at the main function and run the program. Execution will stop at the breakpoint.
Inspect Variable Value
gdb ./my_program
(gdb) b my_function
(gdb) r
(gdb) p my_variable
After stopping at a breakpoint, print the current value of a specific variable.
Analyze Core File
gdb ./my_program core.dump
Analyze a core file generated by a program crash to examine the program's state at the time of the crash.
Attach to a Running Process
gdb -p 12345
Attach gdb to a running process with PID 12345 for debugging.
Automatically Execute Commands on Startup
gdb -ex 'b main' -ex 'r' ./my_program
Set a breakpoint at the main function and run the program immediately upon gdb startup.
Installation
gdb is not provided by default on most Linux distributions and needs to be installed as part of the development tools package.
Debian/Ubuntu
sudo apt update && sudo apt install gdb
Install gdb using the APT package manager.
Fedora/CentOS/RHEL
sudo dnf install gdb
Install gdb using the DNF or YUM package manager.
Tips & Notes
Tips and notes for effectively using gdb.
Include Debugging Information During Compilation
To debug with gdb, you must compile your program with the `-g` option to include debugging information. Otherwise, you won't be able to see source code information or variable names.
- Example: `gcc -g myprogram.c -o myprogram`
Frequently Used gdb Commands
Core commands frequently used within the gdb prompt.
- `b <function_name/line_number>`: Set breakpoint
- `r`: Run the program
- `n`: Step to the next line (next)
- `s`: Step into a function (step)
- `p <variable_name>`: Print variable value
- `c`: Continue execution until the next breakpoint
- `q`: Quit gdb
Utilize TUI Mode
Using gdb's Text User Interface (TUI) mode can enhance debugging efficiency by allowing you to view source code, registers, and assembly simultaneously.
- Use `gdb -tui <program>` or the `layout src` command within gdb.