C Compiler, Linker & Execution Flow

Before a C program runs on your computer, it goes through several internal steps like preprocessing, compiling, assembling, and linking. Understanding this flow helps you debug programs, link libraries, and write optimized code.

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.

Full Flow: Source Code β†’ Preprocessor β†’ Compiler β†’ Assembler β†’ Linker β†’ Executable β†’ Loader β†’ Execution

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:

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

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.

βœ” Links standard library functions (printf, scanf, etc.) βœ” Combines multiple .o files βœ” Resolves external references βœ” Produces final **executable file**

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).

7. Execution

After loading, the CPU begins executing instructions starting from main().

βœ” Program starts execution βœ” main() function runs first βœ” Program ends when return statement or exit() is executed

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?

Practice Questions

  1. Explain all stages of the C compilation process.
  2. What is the role of the preprocessor?
  3. What is an object file?
  4. What does the linker do?
  5. Why is the loader required?

Practice Task

Write each stage of the C program execution flow in your own words and also draw a diagram to represent it.