Learning Hub Search Ctrl K

Legacy C++ › 1. Getting Started

Scope, Storage Duration and Linkage

Block/file scope, static, extern, and the One Definition Rule.

intermediate #scope#static#extern#linkage#odr#lifetime

Explanation

Scope is where a name is visible: block, function, class, namespace, or file (global). An inner declaration hides an outer one with the same name.

Storage duration is how long the object lives:

  • automatic: local variables, destroyed at the end of the block;
  • static: globals and static locals, live for the whole program;
  • dynamic: created by new, live until delete.

Linkage is whether a name in one file can refer to the same entity in another:

  • external linkage: ordinary globals and functions, shared across files via extern declarations;
  • internal linkage: static at file scope (or const globals), private to that file.

The One Definition Rule (ODR): an entity may be declared many times but defined exactly once across the program (inline functions and templates have special rules).

Example

#include <iostream>

int counter = 0;                 // global, external linkage
static int hidden = 100;         // internal linkage: private to this file

int nextId() {
    static int id = 0;           // initialized once, keeps value between calls
    return ++id;
}

int main() {
    int x = 1;
    {
        int x = 2;               // hides the outer x
        std::cout << x << "\n";  // 2
    }
    std::cout << x << "\n";      // 1

    std::cout << nextId() << nextId() << nextId() << "\n";   // 123
    std::cout << ::counter << " " << hidden << "\n";         // ::name = global scope
    return 0;
}

In a multi-file program, extern int counter; in a header declares the global; exactly one .cpp contains int counter = 0;.

Common pitfalls

  • Defining a global variable in a header gives each file its own copy and a multiple-definition link error. Declare it extern instead.
  • Returning the address of an automatic variable is undefined behavior.
  • Static initialization order fiasco: globals in different files are initialized in an unspecified order, so one must not use another during initialization.
  • Shadowing makes bugs hard to see; compile with warnings on.

Legacy vs modern

C++11 adds thread_local and makes initialization of function-local statics thread-safe; C++17 adds inline variables to define a global in a header safely. Unnamed namespaces are preferred over file-level static for internal linkage.

Exercises

1. What does static mean on a local variable versus a file-scope variable?

On a local it gives static storage duration (value persists). At file scope it gives internal linkage (hidden from other files).