Site Tools


wiki:cpp-internal-linkage

Table of Contents

C++ Internal linkage

Internal linkage means a symbol (function, variable, or type) is visible only within its translation unit and not to other .cpp files. Declaring with static or in an anonymous namespace gives internal linkage. This prevents linker conflicts and allows using the same name in different translation units.

Use static or anonymous namespaces for helper functions and variables that should not be visible to other translation units.

Example

This example shows internal linkage preventing naming conflicts across files.

// compile: g++ -o internal internal.cpp
// run: ./internal
// description: internal linkage limits visibility to one translation unit
 
#include <iostream>
 
// Method 1: static (internal linkage)
static void helperA() { std::cout << "Helper A\n"; }
 
// Method 2: anonymous namespace (preferred, internal linkage)
namespace {
    void helperB() { std::cout << "Helper B\n"; }
    int internal_counter = 0;
}
 
// External linkage (visible to other translation units)
void public_func() { std::cout << "Public\n"; }
 
int main() {
    helperA();
    helperB();
    public_func();
 
    return 0;
}
wiki/cpp-internal-linkage.md · Last modified: by 127.0.0.1