skip to content

In C++, what distinguishes external, internal and no linkage, and how do static and an unnamed namespace give internal linkage?

level: middleimportance: should knowfreq 55%

answer

  1. can another scope or file name it?
  2. shared, file-private, block-local
  3. static at namespace scope
  4. everything inside namespace { }
  5. const globals are internal by default

basics

~20 s

Linkage decides whether one name in different scopes or files denotes the same entity. External: shared across translation units. Internal: private to one translation unit. No linkage: most block-scope names. static, or an unnamed namespace, makes a namespace-scope name internal.

solid answer

~50 s

**Linkage** is the property of a name that decides whether declarations in other scopes or other translation units can refer to the same entity. **External linkage**: any translation unit can name it, which is the default for functions, non-const variables and classes at namespace scope. **Internal linkage**: only its own translation unit can, so two files may each have a private helper with the same name. **No linkage**: local variables and other block-scope names, visible only in their scope. C++20 added **module linkage** for unexported names in a named module. `static` on a namespace-scope variable or function gives internal linkage. An **unnamed namespace** gives everything declared inside it internal linkage, classes and types included, which `static` cannot do. A namespace-scope `const` variable that is not `volatile`, `inline`, a template or `extern` is internal by default.

code

cpp · 16 lines
cpp
#include <cstdio>

int g_scans = 0;                  // external linkage: other files can name it
static int s_retries = 2;         // internal linkage: this file only
const int k_max_speed = 5;        // const at namespace scope: internal by default

namespace {                       // unnamed namespace: everything inside is internal
struct Filter { double alpha = 0.5; };   // a type, which static cannot mark
double smooth(double prev, double next) { return Filter{}.alpha * (prev + next); }
}

int main() {
    int local = 3;                // no linkage: a block-scope name
    g_scans += local + s_retries + k_max_speed;
    std::printf("%d %.1f\n", g_scans, smooth(1.0, 3.0));
}

go deeper

for a junior

Recall the three common kinds: external is shared across files, internal is private to one file, none is local to a block, and that static or an unnamed namespace makes a global name internal.

for a middle

Explain why const globals are internal by default, why an unnamed namespace can hide types where static cannot, and how linkage differs from storage duration.

for a senior

Catch the costly cases in review: internal-linkage helpers in headers, inline functions that name file-local entities, and large const tables duplicated into every translation unit.

for a principal

Set the convention: file-private code in unnamed namespaces, nothing internal in headers, and a deliberate, minimal set of externally linked names as each component's interface.

## What linkage is A **name** in C++ is declared in some scope. **Linkage** answers one question about it: can a declaration of the same name in **another scope**, possibly in **another translation unit**, refer to the same entity? The standard defines four answers: - **External linkage**: yes, from any translation unit. The linker matches the name across object files. - **Module linkage** (C++20): yes, but only from translation units of the same named module; unexported names in a module get it. - **Internal linkage**: only from scopes in the **same** translation unit. Every file can have its own entity with that name, and they never collide. - **No linkage**: only from the scope where it is declared. Local variables not declared `extern`, function parameters and classes defined inside a function have no linkage. Linkage is about **names and the linker**; it is not storage duration. A `static` local variable has no linkage but static storage duration, and a global `int` has external linkage and static storage duration. The keyword `static` appears in both, with unrelated meanings. ## What gets which linkage at namespace scope | Declaration at namespace scope | Linkage | |---|---| | `int g_scans = 0;` | external | | `void plan();` and `class Planner { };` | external | | `static int s_retries = 2;` | internal | | `static void log_raw();` | internal | | `const int k_max_speed = 5;` | **internal**, by the const rule | | `extern const int k_limit = 5;` | external | | `inline const int k_shared = 5;` | external | | anything inside `namespace { }` | internal | The `const` row comes straight from the standard: a non-template variable of non-volatile `const`-qualified type has internal linkage unless it is declared `extern`, is `inline`, was previously declared without internal linkage, or is declared in a module interface unit or partition. ## static versus the unnamed namespace Both make a namespace-scope name private to its translation unit. The differences: 1. **Reach.** The standard allows `static` only on the declaration of a variable or function, plus structured bindings and anonymous unions. It cannot mark a **class** or a **type alias**; clang merely warns that `'static' is not permitted on a declaration of a type` and ignores it. An unnamed namespace covers everything declared inside it, so a helper `struct Filter` in a `.cpp` file can be made internal only that way. 2. **Grouping.** One `namespace { ... }` block marks a whole set of helpers at once. 3. **Mechanism.** The standard gives an unnamed namespace, and any namespace nested inside it, internal linkage, and names declared in a namespace with internal linkage are internal too. Many style guides therefore put file-private helpers in an unnamed namespace and reserve `static` at namespace scope for the odd variable or function. ## Why internal linkage matters - **No accidental collisions.** Two `.cpp` files can each define a helper `double smooth(double, double)` without a duplicate-symbol link error, and neither can call the other's by accident. - **More room for the optimiser.** A function no other file can call may be inlined everywhere and its out-of-line copy dropped. - **Honest interfaces.** What has external linkage is what other files may use; everything else is visibly private, so a reviewer knows a helper in an unnamed namespace can be changed or deleted after a search of one file. - **Better warnings.** The compiler sees every use of an internal function, so it can report one that is never called; GCC's `-Wunused-function`, enabled by `-Wall`, does this for a non-inline `static` function. ## Where internal linkage goes wrong - **In a header.** A `static` function or an unnamed namespace in a header gives every includer its own copy: duplicated code, separate addresses, separate state in any function-local `static`. - **Inside an inline function.** An inline function in a header must mean the same thing in every translation unit. If its body names a `static` function or something from an unnamed namespace, it refers to a **different** entity in each file, which violates the one-definition rule, with no diagnostic required. - **The const surprise.** `const Config k_defaults{...};` in a header gives each file its own copy, constructed separately. That is harmless for an integer, wasteful for a large table, and a source of confusion whenever code compares addresses.

  • Why is a static or unnamed-namespace function risky inside a header?
    Every translation unit that includes the header gets its own private copy, so code is duplicated, addresses differ, and any function-local `static` exists once per file. Worse, an inline function in a header that calls it refers to a different entity in each file, which violates the one-definition rule without any required diagnostic.
  • Does a class defined inside an unnamed namespace have linkage at all?
    Yes, internal linkage. The unnamed namespace has internal linkage, and a named class declared in a namespace with internal linkage gets internal linkage too. That is why the unnamed namespace, not `static`, is the way to make a helper type private to one `.cpp` file.

  • static at namespace scope gives a variable static storage duration, nothing else.
  • A const global in a header is one shared object across all files.
  • static can make a helper class private to one .cpp file.
  • Local variables have internal linkage.
  • Linkage and storage duration are the same thing.