Main Memory: Allocation, Linking & Segmentation

the linker

Imagine several authors each writing one chapter of a book separately. Chapter 3 says 'see the recipe in Chapter 7', but while writing it nobody knew what page Chapter 7 would land on. Before the book can be printed, an editor must gather all the chapters, decide their order and page numbers, and fill in every 'see page __' reference with the real number. The linker is that editor for programs: it combines separately compiled pieces into one runnable whole and fills in the addresses that connect them.

Concretely, a compiler turns each source file into an object file containing machine code plus a table of symbols it defines (like the function 'sort') and symbols it needs but does not have (like a call to 'printf'). The linker takes all these object files plus library code and does three jobs: it lays them out together into one program image, it resolves symbols (matching each 'I need printf' to the 'here is printf' that some object or library provides), and it performs relocation (adjusting addresses now that everything has a place). The result is an executable file ready to be loaded.

Why it matters: linking is what lets you build big programs out of small, separately compiled files and reuse pre-built libraries instead of rewriting everything. If the linker cannot find a definition for a symbol you used, you get the familiar 'undefined reference' error; if two files both define the same symbol, you get a 'multiple definition' error. The linker runs at build time, before the program ever executes — distinct from the loader, which acts later, at launch.

main.o calls a function add() but only declares it; math.o defines add(). The linker matches the call in main.o to the definition in math.o, places both, fixes the call's target address, and writes one executable.

Combine object files, resolve symbols, relocate — into one executable.

The linker runs at build time and produces the executable; the loader runs later and puts it into memory. An 'undefined reference' is a link error, not a compile error — the code compiled fine but a symbol could not be found at link time.

Also called
link editorld連結程式