GNU Debugger (GDB)

DebuggingC/C++LinuxCommand LineGNUSystem ProgrammingBacktraceBreakpoint

Debugging Tool

GNU Debugger (GDB)

Overview

GDB is the GNU project debugger. It supports languages like C, C++, Go, Rust, enabling bug identification through command-line control of program execution. It's the standard debugging tool in Unix/Linux environments.

Details

The GNU Debugger (GDB) was initially developed by Richard Stallman in 1986 as part of the GNU Project. The latest version is GDB 16.3 (released April 2025), with continuous feature enhancements. GDB provides four main capabilities: "seeing what's happening inside another program while it executes" and "examining what another program was doing when it crashed." It can start programs with specified conditions, stop them under specified conditions, examine what happened when programs stop, and change things in programs for experimental bug fixes.

Operation is primarily through command-line interface, but it also provides TUI (Text User Interface) mode, allowing debugging with source code display using the gdb -tui option. It includes advanced features like multithreaded program debugging, remote debugging, core dump analysis, and reverse execution debugging. Recent versions have enhanced machine code display capabilities.

Development continues actively, and while GUI usage through IDEs has increased, it remains important for server environments and system-level debugging. Using compilation options -g3 -O0 provides the optimal debugging experience.

Pros and Cons

Pros

  • Free and Open Source: Available under GPL license
  • Wide Language Support: Supports C, C++, Go, Rust, Fortran, and more
  • Rich Features: Breakpoints, backtrace, variable inspection, reverse execution
  • Cross-Platform: Runs on Linux, macOS, Windows, FreeBSD
  • Remote Debugging: Network-based debugging capabilities
  • Scripting Support: Python API for automation and customization
  • IDE Integration: Works with Visual Studio Code, Eclipse, CLion
  • System-Level: Kernel debugging and core dump analysis

Cons

  • High Learning Curve: Command-line operation mastery required
  • Beginner Barrier: Basic Unix/Linux knowledge prerequisite
  • Performance Impact: Program execution slowdown during debugging
  • Limited GUI: Primarily text-based interface
  • Complex Setup: Complicated configuration for advanced features
  • Technical Error Messages: Can be difficult for beginners to understand
  • Multiprocess Complexity: Complexity when debugging multiple processes

Key Links

Usage Examples

Program Compilation and GDB Startup

# Compile with debug information
gcc -g3 -O0 -o myprogram myprogram.c

# Start program with GDB
gdb ./myprogram

# Start with TUI mode (source code display)
gdb -tui ./myprogram

# Attach to existing process
gdb -p <process_id>

# Core dump analysis
gdb ./myprogram core

Basic GDB Commands

# Run program
(gdb) run
(gdb) r

# Run with arguments
(gdb) run arg1 arg2
(gdb) set args arg1 arg2
(gdb) run

# Set breakpoints
(gdb) break main
(gdb) b main
(gdb) break 25          # Line 25
(gdb) break myfile.c:25 # Specify file
(gdb) break func_name   # Function name

# List breakpoints
(gdb) info breakpoints
(gdb) info b

# Delete breakpoints
(gdb) delete 1          # By number
(gdb) clear            # Current location

Program Execution Control

# Step execution (step into function calls)
(gdb) step
(gdb) s

# Next execution (step over function calls)
(gdb) next
(gdb) n

# Continue execution
(gdb) continue
(gdb) c

# Finish current function
(gdb) finish

# Run until specified line
(gdb) until 30
(gdb) u 30

Variable and Memory Inspection

# Print variable values
(gdb) print variable_name
(gdb) p variable_name
(gdb) p *ptr                # Dereference pointer
(gdb) p array[0]            # Array element
(gdb) p struct_var.member   # Struct member

# Display type information
(gdb) ptype variable_name
(gdb) whatis variable_name

# Memory dump
(gdb) x/10x $sp            # 10 words from stack pointer
(gdb) x/s string_ptr       # Display as string
(gdb) x/i $pc              # Display as instruction

# Change variable values
(gdb) set variable_name = new_value
(gdb) set var i = 10

Backtrace and Stack Information

# Display call stack
(gdb) backtrace
(gdb) bt
(gdb) bt full              # Include local variables

# Navigate stack frames
(gdb) frame 0              # Move to frame 0
(gdb) f 0
(gdb) up                   # Upper frame
(gdb) down                 # Lower frame

# Display frame information
(gdb) info frame
(gdb) info locals          # Local variables
(gdb) info args            # Arguments

Advanced Debugging Features

# Conditional breakpoints
(gdb) break 25 if i == 100
(gdb) condition 1 i == 100  # Add condition to existing breakpoint

# Watchpoints (stop when variable changes)
(gdb) watch variable_name
(gdb) rwatch variable_name  # On read
(gdb) awatch variable_name  # On read/write

# Function calls
(gdb) call function_name(args)
(gdb) call printf("Debug: %d\n", i)

# Multithreaded debugging
(gdb) info threads         # List threads
(gdb) thread 2             # Switch to thread 2
(gdb) thread apply all bt  # Backtrace for all threads

Remote Debugging

# Target side (program to debug)
gdbserver :1234 ./myprogram

# Host side (GDB execution)
gdb ./myprogram
(gdb) target remote hostname:1234
(gdb) continue

GDB Scripts and Customization

# Initial settings in .gdbinit file
set confirm off
set verbose off
set prompt (my-gdb) 
set logging on
set print pretty on

# Define custom commands
define print_and_continue
    print $arg0
    continue
end

# Python scripting
python
import gdb
class MyCommand(gdb.Command):
    def __init__(self):
        super(MyCommand, self).__init__("mycommand", gdb.COMMAND_USER)
    
    def invoke(self, arg, from_tty):
        print("Custom command executed")

MyCommand()
end

TUI Mode Operations

# Enable/disable TUI
(gdb) tui enable
(gdb) tui disable

# Window switching
Ctrl+X, A       # Switch active window
Ctrl+X, 1       # Source window only
Ctrl+X, 2       # Source + assembly

# Scrolling
Page Up/Down    # Scroll source code
Ctrl+P/N        # Command history