When your C project grows beyond a single main.c into multiple modules (math_utils.c, network.c, logger.c), debugging with printf() statements becomes chaotic. Using GDB (GNU Debugger) allows you to step into functions located in separate files, inspect variable stack frames, and catch segmentation faults right where they happen.

Step 1: Compile All C Source Files with -g DWARF Symbols

GDB requires debug symbols (file names, line numbers, and variable names) embedded into the executable binary. Always compile with the -g flag:

Terminal Compilation Commandbash
# Compile multi-file C project with GCC debug symbols
gcc -g -Wall main.c math_utils.c logger.c -o app_debug
 
# Launch GDB on the compiled executable
gdb ./app_debug

Step 2: Setting Breakpoints Across Separate Source Files

In GDB, you can set breakpoints in files that are not currently displayed by specifying the filename:line or filename:function syntax:

GDB Interactive Command Sessiontext
(gdb) # Break at function inside math_utils.c
(gdb) break math_utils.c:calculate_factorial
 
(gdb) # Break at specific line inside logger.c
(gdb) break logger.c:45
 
(gdb) # Start program execution
(gdb) run
 
(gdb) # Step INTO function in another file
(gdb) step
 
(gdb) # Print local variable in current stack frame
(gdb) print result
 
(gdb) # View full call stack trace across files
(gdb) backtrace

Essential Multi-File GDB Commands:

  • `step` (or `s`): Steps INTO the function call, jumping execution directly to the source file where the function is defined.

  • `next` (or `n`): Steps OVER the function call, executing it without entering the separate file.

  • `backtrace` (or `bt`): Displays the call stack history showing caller functions and line numbers across all source files.