Lecture 7 · Linking

Introduction to Computer Systems · Lecture 07。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 7 (Sep 15), slide deck 07-linking. Reading: CS:APP3e chapter 7. Lab: L2 (bomblab) is due; L3 (attacklab) is out. Sources: the public Fall 2026 slides and CS:APP. The code is original to these notes and runs the real toolchain (cc, nm, objdump, ar, dlopen) on an Apple M4 Pro (macOS, clang 21); the relocation demo cross-compiles to x86-64 under the same cross toolchain used in Lectures 3–6, so its relocation types match the slides. macOS/Linux differences (.dylib vs .so, DYLD_INSERT_LIBRARIES vs LD_PRELOAD, Mach-O vs ELF) are handled and pointed out. Code: code/lecture07/. Reading time: ~85 minutes; ~20 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Explain what a linker does — symbol resolution and relocation — and why separate compilation needs it.
  2. Classify a symbol as global, external or local, and read nm output.
  3. Apply the three symbol-resolution rules for duplicate definitions, and explain why a strong/weak mismatch is a silent, dangerous bug.
  4. Read a relocation entry in a .o file and describe what the linker writes in its place.
  5. Build and use a static library (.a), and state the link-order rule.
  6. Explain how a shared library (.so/.dylib) is linked at load time or run time, and how interposition (LD_PRELOAD / __interpose) replaces a function.

0.2 Prerequisites and scope

  • Lectures 3–6: machine code, %rip-relative references (Lectures 5–6), and the process memory layout (Lecture 6). Linking is what fixes the addresses those references use.
  • In scope: CS:APP chapter 7 — the compiler driver, symbols and resolution, strong/weak rules, ELF/Mach-O object files, relocation, static and shared libraries, dynamic linking (load-time and run-time), and library interposition.
  • Position-independent code and the PLT/GOT are described in enough depth to connect to the %rip-relative and @GOTPCREL references seen in Lectures 5–6; CS:APP §7.12 has the full detail.

0.3 Section → code map

SectionIdeaDemo in code/lecture07/
§1why a linker; the compiler driver—
§2symbols: global / external / local01_symbols.py
§3symbol resolution; the strong/weak rules01_symbols.py
§4relocation02_relocation.py
§5static libraries; link order03_static_libraries.py
§6shared libraries; dynamic linking04_shared_libraries.py
§7interposition04_shared_libraries.py

1. Why linkers?

1.1 The compiler driver hides the steps

You type cc main.c sum.c -o prog and get a program. Behind that one command, the compiler driver runs a pipeline for each source file:

main.c --[preprocess cpp]--> main.i --[compile cc1]--> main.s --[assemble as]--> main.o
sum.c  --[            same pipeline              ]-->                            sum.o
main.o + sum.o + libraries --[link ld]--> prog

The first stages turn each .c into a relocatable object file (.o) independently. The last stage, the linker, combines them into one executable. This lecture is about that last stage.

1.2 What linkers buy you

  • Modularity. A program can be many source files and can use libraries written by other people. You compile each file once.
  • Efficiency in time. Change one file, recompile only it, relink. A big program’s make recompiles a handful of files, not all of them.
  • Efficiency in space. With shared libraries, one copy of libc on disk and (roughly) one in memory serves every program, instead of baking a copy into each (§6).

The price is a set of rules — about duplicate symbols, link order, and library kinds — that produce some of the most confusing errors a C programmer meets. Understanding the linker turns “undefined reference to foo” and “two strong symbols” from mysteries into one-line fixes.

1.3 The two jobs

A linker does exactly two things:

  1. Symbol resolution (§2–3): every use of a global name (a function call, a global variable reference) must be matched to exactly one definition.
  2. Relocation (§4): now that it knows where every piece of code and data will sit, the linker fills in the final addresses that the compiler left blank.

2. Symbols

2.1 Definitions and references

The slides’ example, two files:

/* main.c */                              /* sum.c */
int sum(int *a, int n);                   int sum(int *a, int n) {
int array[2] = {1, 2};                        int i, s = 0;
int main(int argc, char **argv) {             for (i = 0; i < n; i++)
    int val = sum(array, 2);                      s += a[i];
    return val;                               return s;
}                                         }

main.c defines main and array, and references sum and array. sum.c defines sum. A symbol is a name the linker tracks across modules. There are three kinds (CS:APP §7.5):

  • Global: defined by this module and usable by others — a non-static function or global variable. (main, array, sum.)
  • External: referenced by this module but defined in another — what this module needs the linker to find. (sum, as seen from main.o.)
  • Local: defined and used only within this module — a static function or static global. These never clash across files.

Local linker symbols are not local program variables. An ordinary non-static local variable lives on the stack (Lecture 5) and has no linker symbol at all. A static local variable does get a (uniquely renamed) linker symbol, because it has one fixed storage location.

2.2 Reading symbols with nm

01_symbols.py PART A compiles the two files and lists their symbols:

  main.o:
    _array     D   GLOBAL, defined here (initialized data)
    _main      T   GLOBAL, defined here (text/code)
    _sum       U   EXTERNAL: referenced here, defined elsewhere
  sum.o:
    _sum       T   GLOBAL, defined here (text/code)

nm’s letter gives the kind and the section: uppercase = global, lowercase = local; T/t = text (code), D/d = initialized data, B/b = .bss (zero-initialized), C = common (a tentative/weak definition), U = undefined (an external reference). The linker’s core task is now visible: match main.o’s U _sum to sum.o’s T _sum. (Names carry a leading _ on macOS; Linux has none.)


3. Symbol resolution and the strong/weak rules

3.1 Strong and weak symbols

Resolution is easy when each global is defined once. The hard case is duplicate definitions, and C’s rules here are a notorious source of silent bugs. Each definition is strong or weak:

  • Strong: a function, or an initialized global variable (int x = 5;).
  • Weak: an uninitialized (“tentative”) global variable (int x;), or one declared extern without a definition.

The three rules (CS:APP §7.6.1):

  1. Two strong symbols with the same name → link error. Each thing may be defined once.
  2. One strong and one or more weak → the strong one wins. Every reference resolves to the strong definition.
  3. Several weak and no strong → the linker picks one arbitrarily. All of them end up sharing that one storage location.

Demo 01 PART B runs them:

  Rule 1 (two STRONG definitions of x is an error):
      strong1.o + strong2.o    LINK ERROR: duplicate symbol '_x'
  Rule 3 (two WEAK definitions -> the linker picks one, silently):
      weak1.o + weak2.o        LINKS (no error)

Rule 1 behaves as advertised. Rule 3 is the trap: two files each wrote int x;, believing they own a private global, but after linking they share one location. A write to x in one file silently changes x in the other — the “Is this what you really want?” of the slides.

Modern toolchains, and 2027. Many current compilers default to -fno-common, which makes even Rule 3 a link error (two tentative definitions clash). The slides include “in 2027” variants acknowledging this shift. The toolchain these notes run on still uses “common” symbols by default, so Rule 3 demonstrates the classic behavior; cc -fno-common turns it into an error there too.

3.3 The dangerous mismatch

Rule 2 is the quiet killer when the types disagree. Demo 01 PART C:

/* def_double.c */  double x = 3.14;   (strong)   /* use_long.c */  long x;  (weak)
                                                   void clobber(void) { x = -1; }
  main sees x = 3.14
  after clobber, x = nan

use_long.c’s weak long x resolves (Rule 2) to the strong double x, so both names are the same 8 bytes, viewed as incompatible types. clobber() writes the integer -1 into them, and main reads it back as a double: 3.14 has become nan. This links with no error and no warning. It is the slides’ “Evil!” puzzle, and it is exactly the kind of bug that eats an afternoon.

The practical advice (slides “Global Variables”): avoid globals where you can; otherwise make them static if they are file-private; initialize the ones you define; and use extern only to reference a global defined elsewhere, never to define one.


4. Relocation

4.1 Placeholders and relocation entries

The compiler turns each .c into a .o without knowing where anything will finally live — that depends on how all the modules are laid out, which only the linker sees. So wherever an address belongs, the compiler writes zero placeholder bytes and attaches a relocation entry telling the linker what to patch. 02_relocation.py PART A, on main.o compiled to x86-64:

  _main:
       4: 48 8d 3d 00 00 00 00   leaq _array(%rip), %rdi
      11: e9 00 00 00 00         jmp  _sum
  Relocation entries:
      00000012  BRANCH  _sum       (PC-relative call/jmp target)   = ELF R_X86_64_PLT32
      00000007  SIGNED  _array     (%rip-relative data reference)  = ELF R_X86_64_PC32

Both address fields are 00 00 00 00. The two relocation entries say “at this offset, patch in the address of this symbol, in this form”. Mach-O names them X86_64_RELOC_BRANCH / _SIGNED; ELF calls the same two R_X86_64_PLT32 / R_X86_64_PC32. Same idea.

4.2 After linking

PART B links the two modules and disassembles the result:

  _main:
    1000003d4: 48 8d 3d 25 0c 00 00   leaq _array(%rip), %rdi
    1000003e1: e9 0a 00 00 00         jmp  _sum

The placeholders are gone. The jmp arithmetic checks out, exactly as you decoded calls by hand in Lecture 3:

  jmp at 0x1000003e1, 5 bytes long, so next instruction = 0x1000003e6
  displacement = 0x0a (10); target = 0x1000003e6 + 10 = 0x1000003f0 = _sum

and _sum is indeed at 0x1000003f0. The data reference leaq _array(%rip) got a %rip-relative displacement the same way. No relocation entries remain — the linker consumed them. Running it returns 1 + 2 = 3. This is why the same .o can land at different addresses in different programs: nothing is committed until link time (and, for a position-independent executable, until load time — Lecture 6’s ASLR).


5. Static libraries

5.1 What they are

You do not want every program to recompile printf. The old solution is a static library: an archive (.a) bundling related .o files with an index of their symbols. 03_static_libraries.py PART A builds one from the slides’ vector library:

  ar rcs libvector.a addvec.o multvec.o   ->  members: addvec.o, multvec.o

Nothing is linked yet; a .a is a container the linker can search.

5.2 Only what you use

When you link against a library, the linker pulls in only the members that resolve references it has seen, not the whole archive. PART B links main2 (which calls addvec but not multvec):

  addvec present:  yes
  multvec present: no
  ./client -> z = [4 6]

addvec.o was copied out of the archive; multvec.o was left behind, because nothing referenced it. A static library is resolved member by member.

The linker scans the command line left to right, carrying a set of still-unresolved references. When it reaches a library, it takes only the members that satisfy references seen so far. So a library must come after the code that uses it:

  cc main2.o libvector.a    -> links
  cc libvector.a main2.o    -> (classic ld:) undefined symbol addvec

With the library first, the linker has no pending references yet, so it takes nothing from it; then main2.o’s reference to addvec has nothing left to resolve against. (The toolchain these notes run on happens to tolerate the reversed order; GNU ld does not. For libraries that depend on each other, -Wl,--start-group ... --end-group lets the linker loop.) The habit: objects first, then the libraries they need.


6. Shared libraries

6.1 Why

Static libraries have real drawbacks (slides §43): every executable carries its own copy of libc (disk waste), every running process has its own copy in memory (RAM waste), and a security fix in a library means relinking every program that used it. The modern answer is a shared library (.so on Linux, .dylib on macOS, “DLL” on Windows): code and data linked into a program as it runs, not baked into the executable.

04_shared_libraries.py PART A builds one and shows that the client only records a dependency:

  built libvector.dylib
  the executable's library dependencies (otool -L):
    @rpath/libvector.dylib ...
    /usr/lib/libSystem.B.dylib ...

client_dyn does not contain addvec’s code; it says it needs libvector at run time. One copy of the library on disk serves every program that links it, and a bug fix in the library reaches all of them with no relinking. (otool -L on macOS, ldd on Linux, lists these dependencies.)

6.2 Load-time vs run-time linking

A shared library can be linked in two ways:

  • At load time: the program names the library at link time (-lvector), and when it starts, the dynamic linker maps the library in and resolves the references before main runs. This is the usual case (every C program does it for libc).
  • At run time: the program names the library as a string and asks for it explicitly, with dlopen/dlsym. This is how plugins work — code chosen while the program runs. PART B runs the slides’ dll.c:
void *handle = dlopen("./libvector.dylib", RTLD_LAZY);  // find + map the library now
void (*addvec)(...) = dlsym(handle, "addvec");          // look up a symbol by name
addvec(x, y, z, 2);
dlclose(handle);                                        // unmap it
  ./dll ./libvector.dylib  ->  z = [4 6]

dll was built with no -lvector: it discovers the library entirely at run time.

6.3 Position-independent code (a note)

For one on-disk copy of a library to be shared by many processes, each of which loads it at a different (randomized, Lecture 6) address, the library’s code must run correctly wherever it is mapped, without the linker patching it per process. That is position-independent code (PIC): it reaches globals and calls through a per-process Global Offset Table (GOT) and Procedure Linkage Table (PLT), addressed %rip-relative. This is exactly the _array(%rip) and sym@GOTPCREL(%rip) forms you met in Lectures 5–6. CS:APP §7.12 has the mechanism; the one-line summary is: the %rip-relative references exist so that code need not be relocated at load time.


7. Interposition

Because a shared function is bound at load time, you can slip your own version in front of it without touching the program. 04_shared_libraries.py PART C does this with a square function. Normally:

  square(1) = 1   square(2) = 4   square(3) = 9   square(4) = 16

With a tracing interposer loaded first:

  square(1) = 1001   square(2) = 1004   ...
  [interposed] square(1) = 1, returning 1001
  ...

The same unmodified binary now calls the interposer, which calls the real square, prints a trace, and adds 1000. The three ways to interpose (CS:APP §7.13):

  • Compile time: a macro or header redirects calls before compilation.
  • Link time: e.g. GNU ld’s --wrap symbol.
  • Run time: the dynamic linker. On Linux, set LD_PRELOAD to a library that defines square; it calls the real one via dlsym(RTLD_NEXT, "square"). On macOS, the two-level namespace binds square directly, so you use a __DATA,__interpose table instead; dyld then redirects callers, and the replacement can still call the original. The demo ships both and picks the right one.

Interposition is how a malloc tracer, a leak checker, or a mock in a test is slipped under a program — and, less happily, how malware can hijack a function. It is the practical payoff of understanding that linking can happen at load time.


Summary

  • A linker combines relocatable .o files into one program by doing two jobs: symbol resolution (match each reference to one definition) and relocation (fill in the final addresses).
  • A symbol is global (defined here, usable elsewhere), external (used here, defined elsewhere — nm’s U) or local (static). nm’s letter gives kind and section.
  • Resolution rules: two strong definitions → error; strong beats weak; several weak → one is chosen and shared. A strong/weak type mismatch links cleanly and corrupts data (a double became nan). Avoid globals; use static; initialize; extern only references.
  • Relocation: the compiler leaves zero placeholders plus relocation entries; the linker patches a data reference to a %rip-relative offset and a call to a PC-relative displacement (which adds up exactly).
  • A static library (.a) is an indexed bundle; the linker pulls in only the members that resolve pending references, scanning left to right, so libraries come after the objects that use them.
  • A shared library is linked at load time (named with -l) or run time (dlopen/dlsym), so one on-disk copy serves all programs and fixes need no relinking. Interposition (LD_PRELOAD / __interpose) replaces a function in an unmodified binary.

Common pitfalls

  • undefined reference to foo almost always means a missing object/library, or a library listed before the code that uses it. Check link order first.
  • Two files with int x;. On an old toolchain they silently share storage (Rule 3); on a modern one they fail to link. Either way, make file-private globals static.
  • extern int x; with no definition anywhere. A weak reference that links only if some file defines x; otherwise an undefined-symbol error at link time.
  • A struct/type changed in a header but not everywhere recompiled. Offsets baked into one .o no longer match another’s — a linking-era version of Lecture 6’s struct-mismatch bug. Rebuild all dependents.
  • Running a program that needs a shared library not on the search path. dlopen/the loader fails at run time, not at link time. Set LD_LIBRARY_PATH/DYLD_LIBRARY_PATH or an rpath.
  • Expecting LD_PRELOAD to work on macOS. Use the __interpose mechanism there instead.

Exercises

  1. Classify. In static int k = 3; int g; extern int h; int f(void){ return g + h + k; }, classify each of k, g, h, f as global/external/local and strong/weak.

    Answer`k`: local (static), strong (initialized) — a local *linker* symbol. `g`: global, weak (tentative). `h`: external (referenced, defined elsewhere) — a weak reference. `f`: global, strong (a function).
  2. Resolve. File a: int x = 1; int y;. File b: int x; double y = 2.0;. What does the linker do with x and with y?

    Answer`x`: one strong (a's `int x = 1`) and one weak (b's `int x;`) → Rule 2, both resolve to the strong `int x = 1`. `y`: one weak (a's `int y;`) and one strong (b's `double y = 2.0`) → Rule 2, both resolve to the strong `double y` — and a's code using it as an `int` is a type-mismatch bug. (On `-fno-common`, `x` still links by Rule 2; two *strong* definitions would be the error.)
  3. Order. libm provides sqrt, used in calc.o. Which of cc calc.o -lm and cc -lm calc.o links, and why?

    Answer`cc calc.o -lm`. The linker sees `calc.o`'s unresolved `sqrt` first, then pulls `sqrt` from `libm`. With `-lm` first there are no pending references when it scans `libm`, so it takes nothing, and `sqrt` is then unresolved.
  4. Relocation. A .o has e8 00 00 00 00 call foo at offset 0x20, with a PC-relative relocation for foo. After linking, the instruction is at 0x401000 and foo is at 0x402000. What 4 displacement bytes does the linker write?

    AnswerThe call is 5 bytes, so the next instruction is 0x401005. displacement = target − next = 0x402000 − 0x401005 = 0xFFB (4091). Little-endian bytes: `fb 0f 00 00`.
  5. Static vs shared. Give one advantage of a static library over a shared one, and two advantages of shared over static.

    AnswerStatic: the executable is self-contained — no run-time dependency to find or version-match. Shared: less disk and memory (one copy serves all programs), and a library bug fix reaches every program without relinking. (Also: run-time loading enables plugins.)
  6. dlopen. Why can a plugin architecture use dlopen/dlsym but not ordinary -l linking?

    Answer`-l` names the library at *link* time, so the set of plugins must be known when the program is built. `dlopen` takes the library *name as a string at run time*, so a program can load plugins discovered later (from a directory, a config file, user choice) without being rebuilt.
  7. Interposition. You want to count how many times a program calls malloc, without its source. Sketch the approach on Linux and say how your wrapper calls the real malloc.

    AnswerWrite a library defining `malloc` that increments a counter and forwards to the real one, found with `real = dlsym(RTLD_NEXT, "malloc")`; build it as a `.so` and run the program with `LD_PRELOAD=./libcount.so`. On macOS, use a `__interpose` table instead. (Care: the first `dlsym` may itself allocate, so real tracers bootstrap carefully.)
  8. The mismatch again. Why does the double x / long x bug in §3.3 link with no warning, when the compiler would reject double x; long x; in one file?

    AnswerWithin one translation unit the compiler sees both declarations and flags the conflict. Across files the compiler sees only one each; the conflict is only visible at link time, and the linker tracks names and sizes, not C types, so it silently resolves them to one location. This is why cross-module type agreement relies on shared headers.

Linking is not a lab of its own, but it underlies both. bomblab (due today) is read with objdump/gdb, and knowing which addresses are relocated vs PC-relative (§4) helps you follow jumps and global references in the disassembly. attacklab (out today) builds directly on Lecture 6’s stack material; this lecture’s relocation and memory-layout view explains why addresses in the target are where they are. As always, these notes carry no lab solutions.

Further reading

  • CS:APp3e chapter 7 in full; practice problems 7.1–7.13. §7.12 (PIC, GOT/PLT) and §7.13 (interposition) for the parts summarized here.
  • man nm, man objdump / man llvm-objdump, man ar, man 3 dlopen, man ld, man dyld.
  • The ELF specification and the Mach-O format reference, for the object-file layouts (§7.4 covers ELF).
  • Levine, Linkers and Loaders (1999), the standard book-length treatment.
  • The glibc getaddrinfo CVE the slides cite (CVE-2015-7547), a real case where a shared-library fix updated every program at once.

Preview of Lecture 8: Design and debugging

You have now followed a program from C through machine code (3–6) to a linked executable (7). Lecture 8 steps back to method: how to find a bug on purpose instead of by luck. It covers the vocabulary (defect → error → failure), scientific debugging (hypothesis → prediction → experiment → observation), the compiler flags and tools that catch whole classes of bug (-Wall, gdb/lldb, valgrind, the sanitizers you already met in Lecture 1), and design habits — modularity, invariants, assertions — that keep bugs from arising. Several of the bug classes it debugs are the ones you have just seen: uninitialized data, a symbol mismatch, a use-after-free.


术语表 (Glossary, English → 中文)

English中文
linker / linking链接器 / 链接
compiler driver编译器驱动程序
relocatable object file可重定位目标文件
executable object file可执行目标文件
shared object file共享目标文件
symbol符号
symbol table符号表
definition / reference定义 / 引用
symbol resolution符号解析
global / external / local symbol全局 / 外部 / 局部 符号
strong / weak symbol强 / 弱 符号
tentative (common) definition暂定(公共)定义
relocation / relocation entry重定位 / 重定位条目
placeholder占位符
PC-relative referencePC 相对引用
absolute reference绝对引用
ELF (Executable and Linkable Format)ELF 格式
Mach-OMach-O 格式(macOS)
section (.text / .data / .bss)节(代码 / 数据 / 未初始化数据)
static library (archive, .a)静态库(归档文件)
archiver (ar)归档工具
link order链接顺序
shared library (.so / .dylib / DLL)共享库(动态库)
dynamic linker / loader动态链接器 / 加载器
load-time linking加载时链接
run-time linking运行时链接
dlopen / dlsym动态打开 / 查符号
position-independent code (PIC)位置无关代码
global offset table (GOT)全局偏移表
procedure linkage table (PLT)过程链接表
interposition符号插入(拦截)
LD_PRELOAD / __interpose预加载库 / 插入节(macOS)
← 返回课程目录