Lesson 170 +10 XP

Internal and External Linkage

Internal and External Linkage

When a program is split across multiple source files, the compiler needs to know which names are shared. That's linkage.

Translation units

Each .cpp file you compile is a translation unit. A program is built from many translation units, and they must agree on shared names - the linker joins them together.

External linkage (the default)

A global name has external linkage by default: it is visible to every other translation unit in the program. Two files can share a function because it links across them:

// file1.cpp
int add(int a, int b) { return a + b; }   // external linkage

// file2.cpp
int add(int a, int b);    // declaration, links to file1's version

With extern you can also declare a variable that lives in another file:

// file1.cpp
int score = 100;          // definition

// file2.cpp
extern int score;         // "score exists in another file"

Internal linkage (private to the file)

To keep a name private to one translation unit, use static:

static int hidden = 5;    // only visible in this file

A static global is invisible to every other file - two files can each have their own static int hidden with no conflict.

The modern way: unnamed namespaces

Prefer an unnamed namespace over static for internal linkage:

namespace {
    int hidden = 5;       // internal linkage
}

Everything inside an unnamed namespace is internal - it's the modern, preferred style for "this file only".

Summary of the two kinds

  • External linkage: name usable across all translation units (default for globals).
  • Internal linkage: name private to its own file (static or unnamed namespace).

TL;DR

  • A .cpp file being compiled is a translation unit.
  • External linkage (default): the name is visible to other files; share via declarations and extern.
  • Internal linkage: private to one file - use static or an unnamed namespace.
  • extern says a variable or function exists in another file.
  • Prefer unnamed namespaces over static for modern internal linkage.