C - Compilation and Execution Process in C

A C program does not execute directly. It passes through four main stages before producing output:

  1. Preprocessing

  2. Compilation

  3. Linking

  4. Execution


1. Preprocessing

  • Handled by the preprocessor

  • Processes all lines starting with #

  • No machine code is generated at this stage

Main Preprocessor Tasks:

  • Macro expansion (#define)

  • Header file inclusion (#include)

  • Conditional compilation (#if, #ifdef)

  • Removal of comments

Example:

#include <stdio.h>
#define PI 3.14

Output:
A modified source file with expanded macros and included headers.


2. Compilation

  • Handled by the compiler

  • Converts preprocessed code into assembly / object code

  • Checks for syntax errors

Compiler Responsibilities:

  • Syntax checking

  • Type checking

  • Conversion to object code (.obj or .o file)

Example error detected:

int a = "10";   // type mismatch error

If errors exist → compilation stops.


3. Linking

  • Handled by the linker

  • Combines:

    • Object code

    • Library functions

  • Produces a final executable file

Linking Tasks:

  • Resolves function calls (e.g., printf)

  • Combines multiple object files

  • Attaches standard libraries

Example:

printf("Hello");

printf() definition is linked from the standard library.

Output:

  • Executable file (.exe in Windows, a.out in Linux)


4. Execution

  • Handled by the operating system

  • Executable file is loaded into memory

  • Program starts execution from main() function

Example:

int main() {
    printf("Hello World");
    return 0;
}

Output:

Hello World

Flow of Compilation and Execution

Source Code (.c)
        ↓
Preprocessor
        ↓
Compiler
        ↓
Object Code (.o)
        ↓
Linker
        ↓
Executable File
        ↓
Execution (Output)

Summary Table

Stage Tool Used Output Produced
Preprocessing Preprocessor Expanded source code
Compilation Compiler Object code
Linking Linker Executable file
Execution OS Program output

Key Exam Points

  • C is a compiled language

  • Errors can occur during compilation or linking

  • Execution starts from main()

  • Libraries are linked before execution.