The Linking Process
Linking combines object files and libraries into a final executable, resolving symbols and fixing addresses.
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
Related Topics
Related concepts
Explore how C++ code is parsed into an Abstract Syntax Tree (AST). Learn lexical analysis, tokenization, and syntax parsing for systems programming.
Understand the complete C++ compilation pipeline from source code to object files. Learn preprocessing, parsing, code generation, and optimization stages.
Deep dive into dynamic linking — GOT/PLT lazy resolution, shared library creation, SONAME versioning, RPATH/RUNPATH, dlopen plugin systems, LD_PRELOAD, and debugging with LD_DEBUG.
How C++ programs are loaded — ELF segments, the _start to main() chain, dynamic linking with PLT/GOT, ASLR, real readelf/strace/proc maps output, and startup debugging.
C++ compiler optimization lab notebook — compare optimization levels, inspect compiler rewrites, diagnose auto-vectorization, and build production verification commands.
C++ preprocessor visualized: macros, header guards, conditional compilation, and #include directives explained interactively.
