C Compiler, Linker & Execution Flow
What Happens When You Run a C Program?
A C program does not run directly. It passes through a sequence of steps that convert human-readable code into a machine-understandable executable.
1. Source Code (.c File)
You write your program in a plain text file with a .c extension.
hello.c
--------
#include <stdio.h>
int main(){
printf("Hello World");
return 0;
}
2. Preprocessing (Handled by Preprocessor)
The preprocessor handles lines beginning with #.
It performs:
- Header file expansion β includes stdio.h, math.h etc.
- Macro substitution via #define
- Conditional compilation (#if, #ifdef)
- Removing comments
Output: .i file (preprocessed source)
gcc -E hello.c > hello.i
3. Compilation
The compiler converts the preprocessed code into assembly language.
Output: .s file (assembly code)
gcc -S hello.i
- Checks syntax
- Reports errors
- Optimizes the code
- Generates CPU-specific assembly
4. Assembling
Assembler converts assembly code into machine code.
Output: .o file or .obj (object file)
gcc -c hello.s
This object file is NOT ready to runβit still needs linking.
5. Linking
The linker connects your object file with required libraries.
Output: a.exe, a.out, or a named executable
gcc hello.o -o hello
6. Loading
Loader loads the executable file from storage into main memory (RAM).
- Allocates memory for code
- Allocates memory for global variables
- Sets up runtime stack & heap
7. Execution
After loading, the CPU begins executing instructions starting from main().
Full Compilation Process (Diagram)
Source Code (.c)
β
Preprocessor
β
Compiled Code (.s)
β
Assembler
β
Object File (.o)
β
Linker + Libraries
β
Executable File (.exe / .out)
β
Loader
β
Program Execution (CPU)
Why Understanding Execution Flow Matters?
- Makes debugging easier
- Helps understand linking errors
- Improves understanding of memory layout
- Helps when working with multiple source files
- Useful in embedded and system-level programming
Practice Questions
- Explain all stages of the C compilation process.
- What is the role of the preprocessor?
- What is an object file?
- What does the linker do?
- Why is the loader required?