Comprehensive Guide to Using GDB for Debugging C/C++ Programs
This article provides an in-depth tutorial on the GNU Debugger (GDB), covering its purpose, installation, basic and advanced commands, remote debugging, memory analysis, and practical tips for efficiently debugging C/C++ applications on Linux and Windows platforms.
Debugging is a crucial skill for developers, and GDB (GNU Debugger) is a powerful, open‑source command‑line tool that supports many languages such as C, C++, Fortran, and Go, making it the default debugger on Linux systems.
GDB offers rich features: setting breakpoints (including conditional ones), stepping through code, inspecting variables and memory, backtracing call stacks, and extending functionality via Python scripts or plugins. It runs on Linux, Windows (via MinGW or Cygwin), macOS, and embedded platforms.
Installation and startup : Ensure a compiler with debug symbols (e.g., gcc -g -o my_program my_program.c ) is used. Verify GDB installation with gdb -v . Start GDB with the executable ( gdb my_program ) or attach to a running process ( gdb then attach <PID> ).
Basic commands include:
run (r) [args] – start the program.
break (b) file:line or function – set a breakpoint; conditional breakpoints use if expressions.
next (n) – step over a line; step (s) – step into a function.
continue (c) – resume execution until the next breakpoint.
print (p) expr – display variable values or evaluate expressions.
info break (i b) – list all breakpoints.
backtrace (bt) – show the call stack.
Advanced features :
Backtrace ( bt ) reveals the full call chain with arguments, helping locate the source of crashes.
Memory analysis via heap plugins (e.g., source /path/to/gdbheap.py ) can detect leaks and illegal accesses.
Conditional breakpoints ( break func if i > 10 ) and watchpoints ( watch var ) pause execution when specific conditions occur.
Remote debugging uses gdbserver : /path/to/program on the target and target remote : on the host.
Practical tips :
Use TUI mode ( gdb -tui my_program ) for a split view of source code and console.
Define custom commands or scripts (e.g., define my_debug … end ) to automate repetitive debugging steps.
Integrate GDB with IDEs such as Eclipse CDT for a graphical debugging experience while retaining GDB’s capabilities.
By mastering these GDB techniques, developers can efficiently locate and fix bugs, analyze core dumps, and improve the reliability of their C/C++ applications.
Deepin Linux
Research areas: Windows & Linux platforms, C/C++ backend development, embedded systems and Linux kernel, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.