C++ Core
Static (outside classes)
File-scope static = internal linkage; static local = persists across calls.
Concept core idea Watch out easy to get wrong
Concept
Key concepts
staticat file/global scope → internal linkage: symbol visible only in that translation unit (opposite ofextern).- Two same-named non-static globals defined in two TUs → duplicate-symbol link error; bare
extern int x;with no definition → 'undefined reference'. staticlocal variable → initialized once on first entry, retains value between calls, lifetime = whole program, scope = the function. Thread-safe init since C++11.- 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.