The Complete Guide to Debugging C and C++ With GDB
A full guide to GDB for C and C++: building for debugging, crashes, wrong answers, hangs, corruption, threads, core files, remote targets and habits.

GDB is the debugger most C and C++ programmers on Linux end up learning, usually in a hurry, because something is broken and a printf has stopped being enough. It has been around since 1986, it ships with every Linux distribution, it runs on dozens of architectures, and it is the debugger that embedded toolchains, kernel developers and most open-source projects assume you have. It is also a program with several hundred commands, a manual of roughly a thousand pages and a reputation for being hostile. The reputation is mostly undeserved. A working programmer needs about fifteen commands, a handful of habits and a clear picture of what the debugger is doing underneath. This guide is the whole path: how to build a program so it can be debugged, how to approach the four kinds of bug you will meet, which commands answer which questions, and how to set GDB up so that it stays out of your way. The commands and output are from GDB 16.3 on x86-64 Linux with GCC 14 and glibc 2.40, and everything applies to C and C++ alike unless a section says otherwise. Each major topic has its own deeper post in this series, and this guide points to them where the detail is worth reading.
What a debugger does
A debugger is a program that controls another program. It can stop the target at a chosen place, show its memory and registers, let it run one source line at a time, and stop it again when a particular piece of memory changes. To the target program, none of this is visible: it was built normally, contains no debugging hooks and does not know it is being watched.
On Linux, GDB does this through the ptrace system call. When you type run, GDB starts your program as a child process and tells the kernel that it wants to trace it. From then on the kernel stops the child on every signal and on request, and GDB gets to look at it before deciding whether to let it continue. A breakpoint is implemented by overwriting one byte of the program's code in memory with the int3 instruction, which makes the CPU raise a trap when it is reached; the trap becomes a signal, the kernel stops the program and wakes GDB. Stepping uses the CPU's trap flag, which raises the same trap after every instruction. A hardware watchpoint uses the processor's debug registers, which trap on access to an address without any slowdown. The post on how debuggers work covers each mechanism in detail. What matters here is the consequence: while GDB has your program stopped, nothing is running. You are looking at a frozen process, and you can take as long as you like.
Everything GDB shows you comes from two sources. The first is the live process: its memory, registers and threads. The second is the debug information in the executable, a set of tables in the DWARF format that map machine addresses to source lines and describe every function, variable and type. Without the second source, GDB can still show raw addresses and registers, but it cannot say that address 0x1139 is line 5 of sum.c, or that four bytes on the stack are an int called total. That is why the first practical rule of using GDB is about how you compile.
Build for debugging
Compile with -g. That is the flag that makes GCC write DWARF into the executable. It does not change the instructions the compiler generates and does not slow the program down; it makes the file larger on disk, and the extra sections are not loaded into memory at run time.
gcc -g -O0 -Wall -Wextra -o sum sum.cThe -O0 matters nearly as much. With optimisation on, the compiler moves, merges and deletes code. A variable you can see in the source may live in a register for part of its life and nowhere for the rest, a call may be inlined so there is no function to stop in, and next may jump between lines out of order. GDB reports this faithfully, and it looks like GDB is broken. For ordinary debugging use -O0, or -Og, which keeps most of the speed gains that do not destroy debuggability. When the bug only appears in an optimised build, you debug the optimised build and accept the limits; the post on debugging optimised builds explains what to expect and which extra flags help.
Three other flags are worth knowing. -ggdb3 adds macro definitions, so you can print a macro such as BUFFER_SIZE. -fno-omit-frame-pointer keeps a frame pointer register, which makes stack walks more reliable in optimised code. And -Wall -Wextra is not a debugging flag, but half of the bugs you would debug are named by those warnings, so read them first.
In a build system, make sure your flags reach the compile line. A debug build that has -g in one variable and -O2 -s in another produces a stripped optimised binary and a confusing session. For CMake, -DCMAKE_BUILD_TYPE=Debug gives -g; Release gives no -g; RelWithDebInfo gives -g with -O2. For a shipped binary, keep the symbols in a separate file keyed by build ID so production crashes can be read later, and let GDB find it with debuginfod or symbol-file.
You can check that a binary has the information with file.
file sumsum: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=3a7e51c2..., for GNU/Linux 3.2.0, with debug_info, not strippedThe words with debug_info, not stripped are what you want.
The vocabulary of a session
Start GDB on the program. -q skips the banner.
gdb -q ./sumReading symbols from ./sum...
(gdb)The program is loaded but not running. You give GDB instructions at the prompt, and almost all of them can be abbreviated: break is b, run is r, next is n, step is s, continue is c, print is p, backtrace is bt. Pressing Enter on an empty line repeats the last command, which is what makes stepping through code feel quick. Tab completes commands, function names and file names. help COMMAND documents a command and apropos WORD searches all of them.
Four ideas organise everything else. A breakpoint is a place where the program stops. A frame is one function call on the stack, with its own arguments and local variables, and GDB always has one selected. An expression is anything you can write in C, which GDB evaluates in the selected frame, so print x * 2 works. And a stop is the moment GDB gets control, which it always reports with a line saying where: the function, its arguments, the file and the line.
The program for this guide
We need a program to debug. Rather than one contrived program with every bug in it, this guide uses four short ones, one for each kind of failure you will meet: a crash, a wrong answer, a hang and a corruption. Real bugs fall into those four, and each calls for a different first move.
Case 1: the program crashes
A crash is the easiest kind of bug to find, because the operating system stops the program at the moment of failure, and GDB can show you the scene. This program dereferences a null pointer.
#include <stdio.h>
struct config {
int retries;
};
static int read_retries(const struct config *cfg)
{
return cfg->retries;
}
int main(void)
{
struct config *cfg = NULL;
printf("retries=%d\n", read_retries(cfg));
return 0;
}Build it and run it under GDB with no breakpoints at all. You do not need to guess where the bug is; the crash will tell you.
gcc -g -O0 -Wall -Wextra -o crash crash.c
gdb -q ./crash(gdb) run
Starting program: /home/dev/crash
Program received signal SIGSEGV, Segmentation fault.
0x0000555555555145 in read_retries (cfg=0x0) at crash.c:9
9 return cfg->retries;GDB stopped at the instruction that faulted. The report gives the signal, the function, its arguments, and the source line. cfg=0x0 in the function header already tells you the story: the pointer is null. The stop line shows the program counter in front of the file because the faulting instruction is in the middle of the line.
A crash is a question about how the program arrived here, and the call stack answers it.
(gdb) bt
#0 0x0000555555555145 in read_retries (cfg=0x0) at crash.c:9
#1 0x0000555555555170 in main () at crash.c:15Frame 0 is where the program is and frame 1 is its caller. The null pointer was passed in from main at line 15. To see how main came to pass it, move up and look at its variables.
(gdb) up
#1 0x0000555555555170 in main () at crash.c:15
15 printf("retries=%d\n", read_retries(cfg));
(gdb) print cfg
$1 = (struct config *) 0x0
(gdb) info locals
cfg = 0x0up changes which frame GDB uses to resolve names; it does not run anything. In main, cfg is null because line 14 assigned it that way. That is the whole investigation. In a real program, the question is usually "where did this pointer get its value", and the answer is a few frames up, or in a function that returned null on a failure the caller did not check. When the pointer is not obviously null but is garbage, print *cfg shows Cannot access memory at address 0x..., which is the debugger telling you the address is wild. The x command, covered below, shows what is actually in memory around it.
The recipe for any crash is the same: run to the signal, read the stop line, bt, then up to the frame where a variable looks wrong and print the variables in it. Most crashes are solved in under a minute by those four steps, and nothing in them needs a breakpoint. The post on navigating the call stack goes deeper.
Crashes you did not watch: core files
The crash you need to debug often happened somewhere else, on a test machine or at a customer's site, where you could not run GDB. The operating system can save the dead process's memory in a core file, and GDB can read it later. Whether the system saves one depends on a limit on the shell that started the program.
ulimit -c unlimited
./crashSegmentation fault (core dumped)On systems that use systemd, the core is stored by systemd-coredump and listed with coredumpctl list, and coredumpctl gdb opens GDB on the latest one. On others a file named core appears in the working directory, with the name governed by /proc/sys/kernel/core_pattern. Open it with the executable that produced it.
gdb -q ./crash coreReading symbols from ./crash...
[New LWP 80423]
Core was generated by `./crash'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x0000555555555145 in read_retries (cfg=0x0) at crash.c:9
9 return cfg->retries;You are looking at the same stop, from a file. Commands that read memory work: bt, print, info locals, x, info registers. Commands that need a live process do not: next, continue and call all say that the program is not being run. The executable must be the exact build that crashed, and its shared libraries must match, or the stack beyond your own code may be wrong. For crashes in CI, run GDB in batch mode with gdb -q -batch -ex 'bt full' ./crash core, as the post on batch mode shows.
Case 2: the program gives a wrong answer
Wrong answers are harder than crashes, since nothing stops the program. It runs to the end and prints a plausible number. The only evidence is that the number is wrong.
#include <stdio.h>
static double mean(const int *v, int n)
{
int sum = 0;
for (int i = 1; i < n; i++)
sum += v[i];
return (double)sum / n;
}
int main(void)
{
int v[] = {10, 20, 30, 40};
printf("mean = %.1f\n", mean(v, 4));
return 0;
}The mean of 10, 20, 30 and 40 is 25.0. The program prints something else.
gcc -g -O0 -Wall -Wextra -o wrongavg wrongavg.c
./wrongavgmean = 22.5The first move in a wrong-answer bug is to stop the program before the bad value is produced and watch it being made. Break on the function and step.
(gdb) break mean
Breakpoint 1 at 0x1131: file wrongavg.c, line 5.
(gdb) run
Starting program: /home/dev/wrongavg
Breakpoint 1, mean (v=0x7fffffffe0f0, n=4) at wrongavg.c:5
5 int sum = 0;
(gdb) next
6 for (int i = 1; i < n; i++)
(gdb) next
7 sum += v[i];
(gdb) print i
$1 = 1i starts at 1, not 0, which is already the bug, but suppose you had not noticed. Rather than stepping through every iteration by hand, use display to show the interesting values after each step.
(gdb) display i
1: i = 1
(gdb) display sum
2: sum = 0
(gdb) next
6 for (int i = 1; i < n; i++)
1: i = 1
2: sum = 20
(gdb) next
7 sum += v[i];
1: i = 2
2: sum = 20After the first pass the sum is 20, which is v[1]. The element v[0], which is 10, was never added. Two displayed values, and the loop's mistake is visible: the loop begins at element 1. The fix is int i = 0, and the sum then reaches 100, giving 25.0.
This is the core technique for wrong answers: choose the variables that matter, make them print at every stop and step through the code that updates them, comparing what you see to what you expected. The discipline is to say the expectation out loud before you press next. "After this line, sum should be 10." If it is not, you have found the line.
A faster route when you know which variable is wrong but not which line made it wrong is the watchpoint.
(gdb) delete
Delete all breakpoints? (y or n) y
(gdb) break mean
Breakpoint 2 at 0x1131: file wrongavg.c, line 5.
(gdb) run
...
Breakpoint 2, mean (v=0x7fffffffe0f0, n=4) at wrongavg.c:5
5 int sum = 0;
(gdb) watch sum
Hardware watchpoint 3: sum
(gdb) continue
Continuing.
Hardware watchpoint 3: sum
Old value = 0
New value = 20
mean (v=0x7fffffffe0f0, n=4) at wrongavg.c:6
6 for (int i = 1; i < n; i++)The first change to sum is to 20. The expected first value was 10. A watchpoint tells you where a variable changes without your guessing where to stop, which is its value when the bug has spread across many lines. The earlier value, 0 here, is the initial assignment that ran as sum = 0 before the watch was set; stack garbage would show up as a different old value.
Two other tools help in this category. A conditional breakpoint stops only when something unusual is true, such as break mean if n > 100, which saves you from stopping on the thousand good calls to reach the bad one. The post on conditional breakpoints covers conditions and ignore counts. And finish runs until the current function returns and prints the value, which answers "what did this function give back" without stepping through it.
(gdb) finish
Run till exit from #0 mean (v=0x7fffffffe0f0, n=4) at wrongavg.c:6
0x0000555555555191 in main () at wrongavg.c:14
14 printf("mean = %.1f\n", mean(v, 4));
Value returned is $2 = 22.5Case 3: the program hangs
A hang is the opposite of a crash: nothing happens. The program is alive, perhaps burning a CPU, and not making progress. GDB's job is to freeze it and show where it is.
#include <stdio.h>
int main(void)
{
int count = 0;
while (count != 10)
count += 3;
printf("count = %d\n", count);
return 0;
}The loop adds 3 until count equals 10, but 0, 3, 6, 9, 12 never equals 10, so it never ends. Run it in GDB, wait a second and press Ctrl-C.
(gdb) run
Starting program: /home/dev/hang
^C
Program received signal SIGINT, Interrupt.
0x0000555555555140 in main () at hang.c:7
7 count += 3;
(gdb) print count
$1 = 1507329
(gdb) print count % 3
$2 = 0
(gdb) next
6 while (count != 10)
(gdb) next
7 count += 3;Ctrl-C sends SIGINT to the program, GDB catches it, and the program stops wherever it happened to be. The count is a large multiple of 3, and count % 3 is 0, which gives the diagnosis: the value only takes multiples of three, so it can never be 10. The loop line and the two next commands show that the program cycles between lines 6 and 7 forever. The number you see will differ, since it depends on how long you waited.
A hang in a program you did not start under GDB needs attaching. Find the process id and attach.
gdb -q -p 48210Attaching to process 48210
...
0x0000555555555151 in wait_for_flag (id=7) at spin.c:9
9 while (!ready)GDB stops the process where it is. The detach command lets it run again afterwards, and the post on attaching explains the permission check that makes the first attempt fail on many systems. For a hang in a multithreaded program, the single most useful command is thread apply all bt, which prints every thread's stack, so you can see which threads are blocked and on what. Two threads each waiting for a lock the other holds is a deadlock, visible at once. A program waiting in read or poll is not stuck, just idle, and its stack says so.
Case 4: the data is corrupted
The hardest bugs are those where a value is wrong and nothing near the code that reads it explains why. A buffer overflow elsewhere has overwritten it. By the time you look, the culprit has long since run.
#include <stdio.h>
#include <string.h>
struct session {
char name[8];
int level;
};
static struct session current = {"guest", 1};
static void set_name(const char *src)
{
strcpy(current.name, src);
}
int main(void)
{
set_name("administrator");
printf("%s level=%d\n", current.name, current.level);
return 0;
}level should be 1, and the program prints administrator level=1869898098. Nothing assigns to level. Here the hardware watchpoint earns its place. Stop early, ask GDB to watch the variable, and let the program run.
(gdb) break main
Breakpoint 1 at 0x1171: file corrupt.c, line 18.
(gdb) run
...
(gdb) watch current.level
Hardware watchpoint 2: current.level
(gdb) continue
Continuing.
Hardware watchpoint 2: current.level
Old value = 1
New value = 1869898098
0x00007ffff7f2a8b4 in __strcpy_avx2 () from /lib/x86_64-linux-gnu/libc.so.6
(gdb) bt
#0 0x00007ffff7f2a8b4 in __strcpy_avx2 () from /lib/x86_64-linux-gnu/libc.so.6
#1 0x0000555555555168 in set_name (src=0x555555556004 "administrator") at corrupt.c:13
#2 0x0000555555555190 in main () at corrupt.c:18The CPU trapped the write and GDB stopped the program on the instruction after it. The backtrace names the culprit: strcpy called from set_name, with an argument longer than the eight-byte field. The number 1869898098 is the bytes r, a, t, o read as an integer, a signature of text overwriting a number. The post on hardware watchpoints covers the four-register limit, scope rules and how to watch memory that has no name.
When you need to see the bytes themselves, the x command examines memory in any format.
(gdb) x/16xb ¤t
0x555555558010 <current>: 0x61 0x64 0x6d 0x69 0x6e 0x69 0x73 0x74
0x555555558018 <current+8>: 0x72 0x61 0x74 0x6f 0x72 0x00 0x00 0x00The letters of "administrator" run through the name field and into the integer after it, which is at current+8. The post on examining raw memory explains the format letters and the byte-order effects.
Reading a stop and an expression
The same few commands appear in every case above, and it is worth knowing them precisely, since the rest of GDB is variations on them.
print EXPR evaluates a C expression in the selected frame. It handles variables, struct members, array elements, pointer dereferences, casts, function calls, and arithmetic, and keeps results in numbered history values $1, $2, so you can reuse them in later expressions. print/x shows hex, print/t binary, print/c characters. print array[0]@5 shows five elements starting at the first, which is how you see an array behind a pointer. ptype EXPR shows a type's full definition, and info locals and info args list every variable in the frame.
list shows source around the current line, list 20,40 a range and list function a function. info line, info source and info frame answer where questions. x/NFU ADDRESS examines memory: N units in format F of size U, so x/8xw $sp shows eight words of the stack in hex and x/s name shows a string.
set var x = 5 changes a variable in the running program, and call f(3) runs a function in it. Both are useful and dangerous: changing the state of a program you are debugging can hide the bug you were looking for, and calling a function that takes locks can deadlock the stopped process.
Stepping, in the order you will use it
next runs one line and stays in the current function. step runs one line and enters a call. finish runs until the current function returns. until and advance run to a later line, and until has the useful property of never going backwards, which gets you out of a loop. continue runs until the next breakpoint or signal. stepi and nexti do the same at the level of machine instructions.
The one rule worth memorising is that next and step differ only on lines that call functions. If you are unsure, use next; if you have stepped into something you did not mean to, finish gets you out. The post on stepping lays out how each interacts with calls, loops and breakpoints in skipped code.
Breakpoints that earn their keep
A plain break on a function or line is the starting point. Four refinements cover nearly everything else. A condition, break f if n > 100, stops only on the call you care about. An ignore count, ignore 1 500, skips the first 500. A temporary breakpoint, tbreak, removes itself after one hit. And commands, attached with commands, run a list of GDB commands automatically when the breakpoint hits, so a breakpoint can print some values and carry on, which turns it into a log line you did not have to compile in.
(gdb) break calibrate
(gdb) commands
>silent
>printf "raw=%d\n", raw
>continue
>endinfo breakpoints lists everything you have set, with hit counts, which is the first thing to check when a breakpoint does not do what you expect. disable and enable toggle without deleting. The dedicated posts on breakpoints and on commands lists go through location syntax, pending breakpoints in shared libraries and the rule that a resuming command ends a list.
Threads and forks
Most real programs are not single-threaded, and GDB's default behaviour surprises people. When one thread hits a breakpoint, GDB stops all threads, and when you resume, it resumes them all. So while you next through one thread's code, the other threads run, and variables they share change under you. info threads lists them, thread N switches, thread apply all bt shows every stack, and set scheduler-locking step makes next and step advance only the current thread, which makes stepping deterministic. Use break location thread N to stop only one thread. The post on multithreaded debugging covers these and the deadlock hazards of freezing threads.
A program that calls fork is followed in the parent by default, and the child runs free, so a breakpoint in the child never fires. set follow-fork-mode child switches, and set detach-on-fork off keeps both processes under control. The post on following forks covers catch fork, catch exec and the exec modes.
Optimised code and missing symbols
Two situations make GDB seem to fail. In an optimised build, variables print as <optimized out>, lines are reordered and functions are inlined. This is the debug information telling the truth: the compiler really did remove the variable or keep it in a register for only part of its life. Rebuild with -Og if you can; if you cannot, use info scope FUNCTION to see which variables have locations, step by instruction, and read registers. The dedicated post lists the flags that help.
The other situation is a library with no symbols. Step into printf and you see assembly, because the C library on your machine has its debug information in a separate package. debuginfod solves this: set DEBUGINFOD_URLS to a server and GDB downloads symbols and source by build ID on demand, after one confirmation prompt. The post on debuginfod covers the prompt, the cache and the privacy side of sending build IDs to a server.
Make GDB yours
A new GDB session starts with settings that suit nobody. Put the ones you want in ~/.gdbinit, which GDB reads at startup.
set pagination off
set confirm off
set print pretty on
set print null-stop on
set history save on
set history size 10000
set breakpoint pending on
set disassembly-flavor intelPagination off removes the "press return to continue" pause, which wrecks scripted runs. Pretty printing puts struct fields on separate lines. History saving keeps your commands between sessions, so the up arrow gives you last week's break command. A project can have its own .gdbinit in its directory, which GDB refuses to read until you trust the directory with add-auto-load-safe-path, a protection against files that run arbitrary commands. The post on .gdbinit has the full list and the safety rules.
Two more habits pay back quickly. First, the text interface: gdb -tui or Ctrl-X A opens source, assembly and register windows that follow the program as you step, and layout split shows source and assembly together. Second, user-defined commands: anything you type more than twice can become a command with define, taking arguments through $arg0 and $argc, with documentation for help. A command that prints a linked list is the classic, and the post on define builds it.
For anything repeated, GDB runs unattended. gdb -batch -ex run -ex bt --args ./prog starts the program, prints the stack when it crashes and exits, which is the form for CI.
Debugging a program on another machine
The target is sometimes not where you are. An embedded board has little memory and no room for a debugger. A container has no GDB installed. A production server should not have a debugger running on it all day. GDB solves this with a split: a small program on the target, gdbserver, controls the process, and your GDB on the workstation does the thinking over a TCP connection.
On the target, start the program under the server.
gdbserver :2345 ./sumProcess ./sum created; pid = 5120
Listening on port 2345On the workstation, load the unstripped copy of the program for symbols and connect.
(gdb) file ./sum
Reading symbols from ./sum...
(gdb) target remote 192.168.1.50:2345
Remote debugging using 192.168.1.50:2345
0x00007ffff7fe4540 in _start () from /lib64/ld-linux-x86-64.so.2
(gdb) break sum
(gdb) continueThe program is running on the target, and everything you type happens on the workstation, with the source and symbols there. To attach gdbserver to a process already running, use gdbserver --attach :2345 PID. The protocol has no authentication or encryption, so reach it over an SSH tunnel, and the program must be built for the target's architecture, with a cross-GDB such as aarch64-linux-gnu-gdb or gdb-multiarch on the workstation. The program's output appears on the target, not in your GDB.
Errors you will see, and what they mean
Some messages come up often enough to recognise on sight.
No symbol table is loaded. Use the "file" command. means the program has no debug information, or no program is loaded. Rebuild with -g.
No symbol "x" in current context. means the selected frame has no variable x. Use up or frame N to move to the function that declares it, or check for a typo.
Cannot access memory at address 0x... means you tried to read an address that is not mapped, usually a null or wild pointer. That is a finding, not a failure of GDB.
The program is not being run. means you used a command that needs a live process, such as next, before run or after the program exited.
Make breakpoint pending on future shared library load? (y or [n]) means the function name is not in the symbol table yet, typically because it lives in a shared library that has not loaded. Answer y, or set breakpoint pending on.
warning: Error disabling address space randomization: Operation not permitted appears inside some containers, where the seccomp profile blocks the personality call GDB uses to turn off randomisation. It is harmless for most debugging, and set disable-randomization off silences it. The related failure, ptrace: Operation not permitted, needs the container's SYS_PTRACE capability or a looser profile.
ptrace: Operation not permitted on gdb -p on a normal machine is the Yama security module, covered in its own post, and the fix is to run as root or start the program under GDB.
Run till exit from ... followed by no return value means the function returned void, or was inlined, or the program exited before it returned.
How to debug: a method
The commands are the easy part. Debugging goes faster if you follow a method, and the method is the scientific one.
First, reproduce the bug reliably. A bug you cannot trigger on demand is one you cannot test a fix for. If it is intermittent, find the smallest input, the fewest threads or the fixed random seed that triggers it, and when it will not hold still, record it with rr so the failing run can be replayed.
Second, form a hypothesis before you look. "I think cfg is null because the config file failed to load." A hypothesis tells you which variable to print and what to expect. Without one, you step through code hoping to spot something, which works for twenty lines and fails for twenty thousand.
Third, test the hypothesis with the smallest experiment. A single print or a single breakpoint is enough. If the result matches, you have confirmed a cause; if not, you have eliminated a wrong one, which is progress.
Fourth, narrow the gap between cause and symptom. The bug is where the program's state first becomes wrong, not where it first looks wrong. A crash is a symptom. The null pointer was the cause. The reason the pointer was null is the root. Use up to climb from the symptom, and watchpoints to find the first write of a bad value.
Fifth, change one thing at a time, and keep notes. When you edit the source and rerun, verify that the failure is gone and that the fix addresses the cause you found rather than hiding the symptom. Add a test, so the bug stays fixed.
GDB is a tool for the third and fourth steps. It does not replace thinking, and the best session is often a short one: three commands, a surprised look and an edit.
Where to go from here
This guide covers the daily core of GDB. The next layer is automation and extension: attaching command lists to breakpoints, writing commands in GDB's own scripting language, scripting with Python, writing pretty-printers so your own types print readably, and recording a failing run to step backwards through it. Those topics are the subject of the advanced guide in this series, which starts where this one stops. The LLDB guide covers the other widely used debugger, for macOS and for Clang-based projects. A good order is: use GDB daily for a month with the commands in this guide, read the posts on watchpoints and threads when the first hard bug appears, and learn Python scripting when you notice yourself typing the same loop for the fifth time.
Reading C++ in GDB
Everything above works for C++, and the places where C++ differs are worth listing, since they are where beginners get stuck. Names are the first one. A C++ function has a mangled symbol name in the object file, such as _ZN5Stack4pushEi, but GDB reads the source-level name from the debug information, so you break on Stack::push and see Stack::push (this=0x7fffffffe0d0, value=3) in a frame line. Overloaded functions give a breakpoint with several locations, one per overload, and break 'Stack::push(int)' picks one; quote names that contain parentheses or :: so the shell and GDB do not misread them. info functions push lists every function matching a pattern, including those in libraries, which helps when you do not know the exact name.
Objects are the second. Inside a member function, this is an ordinary variable, and print *this shows the whole object, with base classes as nested structs. print this->count and plain print count both work, since GDB resolves member names in the scope of the frame. For a polymorphic object, set print object on makes print *ptr show the dynamic type, so a Shape * that points at a Circle prints as a Circle, and set print vtbl on shows the virtual table. ptype this prints the class definition with its members and methods, which is the quickest way to recall a layout.
Standard library types are the third. Without help, a std::vector<int> prints as its internals: three pointers named _M_start, _M_finish and _M_end_of_storage inside layers of implementation structs. libstdc++ installs Python pretty-printers that GDB loads automatically when the library is present, after which print v shows std::vector of length 3, capacity 4 = {1, 2, 3}, and std::map, std::string and std::unique_ptr print as their contents. If you see raw internals, the printers are missing or disabled: info pretty-printer lists what is registered, and installing your distribution's libstdc++ debug or GDB-support package usually fixes it. For your own types, you write printers in Python, as the later post on pretty printers shows. print/r v bypasses the printers and shows the raw object, which is the check to use when a printed value looks too tidy to be true.
Templates and inlining are the last. A template function is a separate function for every set of type arguments, so a breakpoint on max may have a dozen locations, and info breakpoints lists them all. Small functions such as std::vector::operator[] are usually inlined even at modest optimisation, and GDB shows them as frames in a backtrace without a call instruction behind them. At -O0 they are real calls and step enters them, which is why stepping through C++ code feels like falling into the library. Use next over lines you trust, and finish to climb out of a library function you entered by mistake. set step-mode on stops stepping from skipping functions without line information, and its default off setting is the right one for most C++ work.
Exceptions need one extra command. A thrown exception unwinds the stack before you can look at it, so by the time the program reports terminate called after throwing an instance of 'std::runtime_error', the frame that threw it is gone. catch throw stops at the throw, with the stack intact, and catch catch stops where one is caught. catch throw is the C++ equivalent of running to a crash: the backtrace shows who threw and why.


