C Compiler & Linking Process

C Tutorial

C Compiler & Linking Process

C Compiler & Linking Process programs go through several stages before becoming an executable. Understanding this helps in debugging, organizing code, and optimizing compilation.


 C Program Compilation Stages

When you run gcc program.c, the process generally involves 4 main stages:

  1. Preprocessing

  2. Compilation

  3. Assembly

  4. Linking


1️⃣ Preprocessing

  • Handled by C Preprocessor (cpp)

  • Processes all preprocessor directives starting with #, like #include, #define

  • Removes comments, expands macros, and includes header files

Example:


 

After preprocessing, the code becomes:

✅ Output: .i file (optional, you can see it with gcc -E program.c -o program.i)


2️⃣ Compilation

  • Converts preprocessed C code into assembly code

  • Checks syntax, type errors, and generates assembly instructions

✅ Output: .s file (assembly code)
Example: gcc -S program.cprogram.s


3️⃣ Assembly

  • Converts assembly code into machine code (object file)

  • Generates .o (or .obj) file

Example: gcc -c program.cprogram.o


4️⃣ Linking

  • Combines one or more object files and library code into executable

  • Resolves symbols (variables/functions used in one file but defined in another)

  • Includes standard libraries like libc

Example:

gcc program.o math.o -o program
  • Output: program (executable)


 Multi-File Project Example

math_utils.c

main.c


 

Compilation Steps:

gcc -c math_utils.c # creates math_utils.o
gcc -c main.c # creates main.o
gcc main.o math_utils.o -o program # Linking
./program # Run

 Compilation Options (GCC)

OptionPurpose
-EPreprocessing only
-SCompile to assembly
-cCompile to object file (no linking)
-o filenameSpecify output file name
-WallEnable all warnings

 Linking Types

  1. Static Linking

    • Libraries are included in executable at compile-time

    • Larger executable, independent of system libraries

  2. Dynamic Linking

    • Libraries loaded at runtime (.so in Linux, .dll in Windows)

    • Smaller executable, system library must exist


🧠 Key Points

  • Each stage produces intermediate files (.i, .s, .o)

  • Linking resolves external symbols between files

  • Understanding compilation helps debug build errors and optimize programs


🔹 Visual Overview

Source Code (.c)

Preprocessor → .i (expanded code)

Compiler → .s (assembly)

Assembler → .o (object)

Linker → executable

You may also like...