Compiling with -g for debug symbols
What you'll learn: How to include a "map" inside your program so debugging tools can link machine code back to your original C source code.
The Secret Map
When you compile a standard C program, the compiler translates your human-readable code into machine code—a series of 1s and 0s that the CPU understands. However, in this translation process, things like variable names and line numbers are usually thrown away to keep the file small and efficient.
Imagine trying to navigate a complex office building where all the room numbers and nameplates have been removed. You can walk around, but you have no idea if you are in "Accounting" or the "Breakroom."
Compiling with the -g flag is like telling the compiler to leave the signs up. It attaches debug symbols to your executable. These symbols act as a map that tells debugging tools exactly which line of C code produced which specific machine instruction.
Using the Flag
To include these symbols, you simply add -g to your gcc command.
#include <stdio.h>
int main() {
int secret_number = 42;
printf("The secret is %d\n", secret_number);
return 0;
}
If you compile normally:
gcc main.c -o my_program
A debugger will see the numbers, but it won't know that the memory address holding 42 was actually named secret_number.
If you compile with the debug flag:
gcc -g main.c -o my_program
Now, when you run this program through a debugger (like GDB or LLDB), the tool can say, "You are currently on line 5, and the variable secret_number is equal to 42."
Why bother?
You might worry that -g makes your program slightly larger. This is true, but it doesn't make the code run any slower. During the development and practice phase, the extra file size is a tiny price to pay for the ability to "see" inside your code. Without -g, if your program crashes, the computer can only tell you it crashed at a cryptic memory address like 0x4005d1. With -g, it can tell you it crashed because of a mistake on line 12.
Key takeaway
Use the -g flag during compilation to bake a "map" into your program, allowing debuggers to show you your actual variable names and line numbers.