Starting GDB with an executable
What you'll learn: How to launch the GNU Debugger and load your program into its controlled environment for analysis.
The X-Ray Machine for Code
Imagine your program is a sealed box. When you run it normally, you see what comes out, but if it crashes, you have no idea what happened inside. GDB (the GNU Debugger) is like an X-ray machine. Instead of just running your code on the bare metal of your computer, you run it inside GDB.
By starting GDB with your executable, you gain the power to freeze time, inspect variables, and see exactly which line of code caused a crash.
Step 1: Prepare the code
Before GDB can help you, you must compile your code with "debug symbols." This tells the compiler to store extra information—like variable names and line numbers—inside the executable. Without this, GDB will see memory addresses but won't know which line of C code they belong to.
Use the -g flag when compiling:
// save as hello.c
#include <stdio.h>
int main() {
int secret_number = 42;
printf("Hello, Debugger!\n");
return 0;
}
Compile it in your terminal:
gcc -g hello.c -o hello
Step 2: Launching GDB
To start the debugger, type gdb followed by the name of your compiled program:
gdb ./hello
When you press Enter, you’ll see a wall of copyright text, followed by a special prompt that looks like this: (gdb).
At this point, your program has not started running yet. You have simply loaded the instructions into the "X-ray machine." GDB is waiting for your command. If you want to actually begin execution, you would type run at the prompt, but for now, notice that GDB has successfully read the symbols from your file. If you see an error saying "no debugging symbols found," you likely forgot the -g flag during compilation.
To leave the debugger and return to your normal terminal, type quit or press Ctrl+D.
Key takeaway
To debug a program, compile with the -g flag and launch it using gdb ./filename to enter the interactive debugging environment.