Lesson 45 of 50 · c
Debugging with GDB
Duration: 12 mins
The GNU Debugger (gdb) lets you step through code, inspect variables, and set breakpoints.
Typical workflow:
- Compile with
-gflag to embed debug symbols. - Start debugging:
gdb ./a.out. - Set breakpoints:
break mainorbreak file.c:line. - Run program:
run arg1 arg2. - Step:
next(line‑wise) orstep(into functions). - Inspect:
print var,info locals. - Continue:
continue. - Quit:
quit.
📚 Example Session (pseudo‑output)
$ gcc -g -o sum sum.c
$ gdb ./sum
(gdb) break main
Breakpoint 1 at 0x4005b6: file sum.c, line 5.
(gdb) run 5 7
Starting program: ./sum 5 7
[New Thread 0x7ffff7fd4700 (LWP 1234)]
Breakpoint 1, main (argc=3, argv=0x7fffffffdfd8) at sum.c:5
5 int a = atoi(argv[1]);
(gdb) next
6 int b = atoi(argv[2]);
(gdb) next
7 printf("%d\n", a + b);
(gdb) print a
$1 = 5
(gdb) print b
$2 = 7
(gdb) continue
12
[Inferior 1 (process 1234) exited normally]
(gdb) quit
📚 Tips
- Use
layout srcfor a source window. watch varstops whenvarchanges.backtrace(bt) shows the call stack after a crash.