- Learn C++ - https://www.learncpp.com -

4.3a — Scope, duration, and linkage summary

The concepts of scope, duration, and linkage cause a lot of confusion, so we’re going to take an extra lesson to summarize everything.

Scope summary

An identifier’s scope determines where it is accessible. An identifier that is out of scope can not be accessed.

Duration summary

A variable’s duration determines when it is created and destroyed.

Linkage summary

An identifier’s linkage determines whether multiple instances of an identifier refer to the same identifier or not.

Identifiers with external linkage will cause a duplicate definition linker error if the definitions are compiled into more than one .cpp file.

There are a few things worth explicitly noting here. First, functions are extern by default, and can be made internal by using the static keyword.

Second, astute readers may note that global types have external linkage, but their definitions don’t cause a linker error when included in multiple files. This is because types, templates, and extern inline functions have an exemption that allows them to be defined in more than one file, so long as the definitions are identical. Otherwise, they wouldn’t be of much use.

Variable scope, duration, and linkage summary

Because variables have scope, duration, and linkage, let’s summarize in a chart:

Type Example Scope Duration Linkage Notes
Local variable int x; Block scope Automatic duration No linkage
Static local variable static int s_x; Block scope Static duration No linkage
Dynamic variable int *x = new int; Block scope Dynamic duration No linkage
Function parameter void foo(int x) Block scope Automatic duration No linkage
External non-const global variable int g_x; File scope Static duration External linkage Initialized or uninitialized
Internal non-const global variable static int g_x; File scope Static duration Internal linkage Initialized or uninitialized
Internal const global variable const int g_x(1); File scope Static duration Internal linkage Must be initialized
External const global variable extern const int g_x(1); File scope Static duration External linkage Must be initialized

Forward declaration summary

You can use a forward declaration to access a function or variable in another file:

Type Example Notes
Function forward declaration void foo(int x); Prototype only, no function body
Non-const global variable forward declaration extern int g_x; Must be uninitialized
Const global variable forward declaration extern const int g_x; Must be uninitialized
4.3b -- Namespaces [1]
Index [2]
4.3 -- Static duration variables [3]