Compiling with debug symbols -g
What you'll learn: How to tell the compiler to include a "map" that allows debugging tools to link your binary code back to your original source code.
The Secret Map
When you compile a standard C program, the compiler translates your human-readable instructions into a lean, mean machine-code machine. In the process, it throws away "useless" information like variable names, function names, and line numbers to keep the file size small.
To a computer, a variable named userAge is just a memory address like 0x7ffe. If your program crashes, a debugger like GDB will tell you the crash happened at a cryptic hexadecimal address. Without a map, you’ll have no idea which line of code that address represents.
The -g flag tells the compiler to create debug symbols. Think of this as a secret map bundled inside your program. It tells the debugger: "Hey, this chunk of machine code at address 0x7ffe actually belongs to the variable userAge on line 12 of main.c."
Using the -g flag
To include these symbols, you simply add the -g flag to your gcc command.
Compare these two commands:
gcc main.c -o my_program(No map included)gcc -g main.c -o my_program(Map included!)
Here is a simple program you might want to debug:
#include <stdio.h>
int main() {
int secret_number = 42;
printf("The secret is: %d\n", secret_number);
// If we crash here, -g lets GDB see the name 'secret_number'
return 0;
}
If you compile the code above with gcc -g, and then open it in GDB, you can type list to see your actual C code or print secret_number to see its value. Without -g, GDB would just shrug and say "No symbol table loaded."
Does it change how the code runs?
Technically, your program will be slightly larger because of the extra map data, but it will behave exactly the same way for the end-user. It’s common practice to use -g during development and only strip those symbols away when you are ready to release the final, polished version to the world.
Key takeaway
Use the -g flag during compilation to include the debug symbols GDB needs to translate machine addresses back into your original variable names and line numbers.