c language · medium

C: static, extern & Linkage

C uses static and extern to control linkage and storage. At file scope, static gives internal linkage, making a variable or function private to its translation unit so other .c files cannot reference it — the idiomatic way to hide helpers and avoid cross-file name clashes; without static, file-scope definitions have external linkage and are visible program-wide. Inside a function, static instead changes storage duration: the variable lives for the entire program and retains its value between calls (initialized exactly once, to its initializer or zero), while remaining visible only within that function — useful for counters, caches, and one-time setup, but it is shared mutable state and therefore not thread-safe without synchronization. extern is a declaration, not a definition: extern int shared; promises the object is defined in some other translation unit so the current file may use it, with the single definition living in exactly one .c. The conventional pattern is to place extern declarations of shared globals in a header and the lone definition in one source file (C++17 inline variables offer an alternative for header-defined globals).

🔑 Key line

C linkage/storage: static at file scope = internal linkage (file-private); static inside a function = static storage (persists across calls, init once, still function-scoped); extern declares a global defined in exactly one other .c.

The code

// file1.c
static int counter = 0; // INTERNAL linkage: private to file1.c
int shared = 0; // EXTERNAL linkage: visible program-wide
void tick(void) {
static int calls = 0; // STATIC storage: persists across calls
++calls;
}
// file2.c
extern int shared; // 'defined elsewhere' — declaration only

What this lesson walks through

  1. 01static at file scope = internal linkage
  2. 02static at block scope = static storage
  3. 03Gotcha — two meanings of static + one definition
  4. 04extern declares, does not define

At file scope, static gives a variable or function INTERNAL linkage: it is private to its translation unit and cannot be referenced from another .c file. Without static, a file-scope definition has EXTERNAL linkage and is visible program-wide. Use static to hide helpers and avoid name clashes across files (the C way to make something 'private').

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of C: static, extern & Linkage and 100+ animated C++ interview lessons.

← Previous
C: const vs #define vs enum
Next →
C: volatile — What It Does (and Doesn't)