C++ Linking Overview
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
dynamic • 156 KB
Provides: sqrt, log, sin +3 more
libc.so
dynamic • 2.1 MB
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
-
- Match undefined symbols with definitions
- Handle name mangling
- Resolve weak/strong symbols
-
Section Merging
- Combine .text sections (code)
- Merge .data sections (initialized data)
- Unite .bss sections (uninitialized data)
-
Relocation
- Adjust addresses to final locations
- Fix function calls and data references
- Update jump targets
-
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
Common Link Commands
# 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
Link Order Matters
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:
- 🔗 Symbol Resolution - How symbols are matched
- 📚 Dynamic Linking - Runtime library loading
- 🎯 Static vs Dynamic - Trade-offs and use cases
What's Next?
After linking creates the executable:
- Program Loading - How the OS loads your program
- Memory Layout - Runtime memory organization