Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

extern — declarations and linkage

extern lets you declare variables and functions while separating a declaration from a definition. It does not mean that the definition must be in another file. It also appears in language linkage specifications such as extern "C" and in explicit instantiation declarations for templates.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

extern int counter;
extern int read_counter();
extern "C" int api_function(int);
extern template class Box<int>;

As a storage-class specifier, extern applies to variables and functions. extern int counter; declares a variable without defining it. Its definition may appear later in the same file or in another translation unit. In the example, the declaration is enough to write read_counter(), while the later int counter = 7; defines the object.

Distinguish declarations from definitions: at namespace scope, extern int counter = 7; is a definition because it has an initializer. A typical multi-file arrangement puts extern int counter; in a header and int counter = 7; in one source file. For this ordinary variable read by the program, exactly one definition is required in the entire program. In the function declaration extern int read_counter();, extern can usually be omitted.

extern does not always force external linkage: a previous declaration can preserve internal linkage, as in static int value; extern int value;. It is not a synonym for module export, either. As a storage-class specifier, it cannot be applied to class members or function parameters.

extern "C" int api_function(int); specifies C language linkage. Language linkage and external linkage are separate properties: in this namespace-scope declaration, api_function has both C language linkage and external linkage. Such specifications are allowed only at namespace scope; the details of interoperability with another language depend on the implementation. Separately, extern template class Box<int>;, with an appropriately defined Box template, is an explicit instantiation declaration: it suppresses the implicit instantiation covered by that declaration, and a required explicit instantiation definition must be supplied in the program. In these two constructs, extern is not a storage-class specifier.

Examples

#include <iostream>

extern int counter;

int read_counter() {
    return counter;
}

int counter = 7;

int main() {
    std::cout << read_counter() << '\n';
}

Result

7

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources