Super Expert C Programming Course - Day 1: How a C Program Runs (Made Simple)
When you write a simple C program like this:
#include <stdio.h>
int main() {
int x = 5;
printf("%d\n", x);
return 0;
You hit Run, and it shows 5. But what really happened?
Step-by-Step: What Happens When You Run a C Program?
1. You Write Code (.c file)
Your code goes into a .c file - it's human-readable.
2. The Compiler Works Its Magic
GCC (or any C compiler) turns your code into machine language in steps:
- Preprocessing - handles #include, #define
- Compiling - turns code into assembly
- Assembling - turns assembly into machine code
- Linking - connects your code with built-in functions (like printf)
This makes an executable file - like a.exe on Windows or a.out on Linux.
3. You Run the Program - Memory is Allocated
The OS gives your program memory to run. Here's a simple memory layout:
Stack - your function variables (like int x = 5)
Heap - used when you use malloc/free
Globals - variables you declare outside main()
Code - your actual C code
So Where is int x = 5; Stored?
Inside the main() function, x is stored in the stack - temporary memory used during function
execution.
BSS (Optional)
Stores uninitialized global/static variables. Example:
int a; // BSS
int b = 5; // Data segment
Summary - Key Takeaways for Today
main() function - Starting point of the program
int x = 5; - Stored in stack memory
Compiler - Translates .c to .exe
Memory Layout - Stack (local), Heap (malloc), Code, Global
printf() - Comes from a library, connected during linking
Your First Expert Assignment:
1. What are the 4 steps of the compilation process?
2. Where is a variable declared inside main() stored?
3. What is the purpose of the stack in a C program?