Systems CourseC/C++ · Linux · Memory
C++ CoreLesson 08 of 441 min read6 questions

Static (outside classes)

File-scope static = internal linkage; static local = persists across calls.

Test yourself ↓

Concept core idea Watch out easy to get wrong

Concept

Key concepts

  1. static at file/global scope → internal linkage: symbol visible only in that translation unit (opposite of extern).
  2. Two same-named non-static globals defined in two TUs → duplicate-symbol link error; bare extern int x; with no definition → 'undefined reference'.
  3. static local variable → initialized once on first entry, retains value between calls, lifetime = whole program, scope = the function. Thread-safe init since C++11.
  4. Global static init order across TUs is unspecified ('static initialization order fiasco'); static locals dodge it (init on first use).
Watch out

Easily confused

static (file) vs extern
static global = internal linkage (private to this file). extern = 'defined elsewhere, share it' (external linkage).
static local vs normal local
A normal local is created/destroyed each call. A static local is created once, keeps its value between calls, and lives for the whole program.

Test yourself

6 questions on this lesson. Write your answers from memory, then compare them with the model answers side by side.