C - Linker and Object File Concepts in C

Object File – Definition

An object file is an intermediate file generated by the compiler after successful compilation of a C source file.
It contains machine-level instructions, but it is not executable.

Typical extensions:

  • .o (Linux/Unix)

  • .obj (Windows)


Contents of an Object File

An object file generally contains:

  1. Machine Code

    • Compiled instructions of functions and statements

  2. Symbol Table

    • Names of variables and functions

    • Indicates whether symbols are defined or undefined

  3. Relocation Information

    • Used by the linker to adjust addresses

  4. Data Section

    • Global and static variables


Types of Object Files

  1. Relocatable Object File

    • Generated by compiler

    • Needs linking to become executable

  2. Executable Object File

    • Final output after linking

    • Ready to run

  3. Shared Object File

    • Used for dynamic linking

    • Example: .so, .dll


Linker – Definition

A linker is a system software tool that combines one or more object files and required libraries to produce a final executable file.


Functions of the Linker

1. Symbol Resolution

  • Matches function calls with their definitions

  • Example: Resolving printf() from standard library


2. Address Binding

  • Assigns final memory addresses to variables and functions


3. Combining Object Files

  • Merges multiple .o files into one executable

Example:

gcc file1.o file2.o

4. Library Linking

  • Links user-defined and standard libraries

  • Handles missing external references


Types of Linking

1. Static Linking

  • Library code is copied into executable

  • Executable size is larger

  • No external dependency at runtime

Example:

gcc -static prog.c

2. Dynamic Linking

  • Libraries are linked at runtime

  • Smaller executable size

  • Shared libraries are reused

Example:

gcc prog.c

Linking Errors

Errors detected during linking are called linker errors.

Examples:

  • Undefined reference to a function

  • Multiple definition of a variable

Example error:

undefined reference to `add`

Difference Between Compiler and Linker

Compiler Linker
Converts source code to object code Combines object files
Checks syntax errors Resolves external symbols
Produces .o file Produces executable
Works on one file at a time Works on multiple files

Program Flow (Simplified)

Source File (.c)
       ↓
Compiler
       ↓
Object File (.o)
       ↓
Linker
       ↓
Executable File