C++ Linking Overview

5 min

Understand how object files are linked together to create executables.

Best viewed on desktop for optimal interactive experience

The Linking Process

Linking combines object files and libraries into a final executable, resolving symbols and fixing addresses.

Linking Process Visualizer

Linking Pipeline

1
Input Processing
Read object files and libraries
Parsing ELF headers and section tables...
2
Symbol Collection
Build global symbol table
3
Symbol Resolution
Match undefined symbols with definitions
4
Section Merging
Combine similar sections
5
Relocation
Fix addresses and offsets
6
Output Generation
Write executable file

Input Object Files

Linked Libraries

libm.so
dynamic156 KB
dynamic
Provides: sqrt, log, sin +3 more
libc.so
dynamic2.1 MB
dynamic
Provides: printf, sprintf, malloc +2 more

Linker Command

ld -o program main.o math.o utils.o -lm -lc --dynamic-linker /lib64/ld-linux-x86-64.so.2

What the Linker Does

  1. Symbol Resolution

    • Match undefined symbols with definitions
    • Handle name mangling
    • Resolve weak/strong symbols
  2. Section Merging

    • Combine .text sections (code)
    • Merge .data sections (initialized data)
    • Unite .bss sections (uninitialized data)
  3. Relocation

    • Adjust addresses to final locations
    • Fix function calls and data references
    • Update jump targets
  4. Library Handling

    • Include needed functions from libraries
    • Static: Copy code into executable
    • Dynamic: Create references for runtime

Types of Linking

Static Linking

# Create static library ar rcs libstatic.a file1.o file2.o # Link statically g++ main.o libstatic.a -o program

Dynamic Linking

# Create shared library g++ -shared -fPIC -o libshared.so file1.o file2.o # Link dynamically g++ main.o -L. -lshared -o program
# Basic linking g++ main.o utils.o -o program # With libraries g++ main.o -lm -lpthread -o program # Specify library path g++ main.o -L/usr/local/lib -lmylib # View symbols nm program # Check dependencies ldd program

Libraries should come after the objects that use them:

# Wrong (may fail) g++ -lmylib main.o # Correct g++ main.o -lmylib # Circular dependencies g++ main.o -lA -lB -lA

Linking Topics

Deep dive into specific aspects:

What's Next?

After linking creates the executable:

If you found this explanation helpful, consider sharing it with others.

Mastodon