A compiler usually translates each source file on its own into an object file. An object file contains machine code, but it cannot run yet: it may call functions defined in other files, and it does not know at which address its own code will end up. Combining object files into an executable is the job of the linker.
Symbols: Who Defines What?
Every object file carries a symbol table. It lists the names the file defines (for example the function main) and the names it uses without defining them. The linker matches every undefined symbol with exactly one definition.
Here T means the symbol is defined in the code (text) section, and U means it is undefined in this file. If no file defines average, linking fails with an “undefined symbol” error; if two files define it, you get a “duplicate symbol” error.
Relocations: Filling in Addresses
When the compiler emits the call to average, it does not know the target address. It leaves a placeholder in the machine code and writes a relocation: “put the address of average at this offset.” Once the linker has decided where every section goes, it walks through the relocations and fills in each placeholder.
Laying Out the Executable
The linker merges sections of the same kind: all code goes into one .text section, read-only data into .rodata. It then gives every section an address and writes the result in the platform's executable format, which is ELF on Linux.
With static linking, the library code that is needed is copied into the executable. With dynamic linking, some symbols are resolved by the dynamic loader when the program starts.
Because the linker sees the whole program at once, whole-program work such as link-time optimization (LTO) and discarding unused sections can also happen at this stage.
Sources
- J. R. Levine. Linkers and Loaders. Morgan Kaufmann, 1999.
- Tool Interface Standard. Executable and Linking Format (ELF) Specification, version 1.2, 1995. refspecs.linuxfoundation.org/elf/elf.pdf
- System V Application Binary Interface, AMD64 Architecture Processor Supplement (relocation types). gitlab.com/x86-psABIs
- LLD – The LLVM Linker. lld.llvm.org