Scope and Linkage

An identifier's scope determines where that identifier can be accessed: within the enclosing block, or within the file. (We say "identifier" because it can refer to a variable, class, or function name.)

An identifier's linkage determines if the identifier is known only to the current file (internal linkage), or to all files (external linkage).

Scope

A variable can only be accessed within its scope.

In addition, only one identifier with the same name can exist in the same scope. However, it is okay if the same identifier names occur in different nesting level.

Local scope

  • A local variable (that is defined inside a function, inside a compound statement block, or is a function parameter) has local scope.
  • They can only be accessed from their definition until the end of the closest enclosing block ({...}).

File Scope

  • A global variable (that is defined outside a function) has file scope.
  • They can be accessed from their definition until the end of the current file.

Linkage

The concept of linkage only applies to global variables and functions.

Local variables have no linkage because the linker won't see it (their scope is limited and they only exist when the function is being called).

Internal linkage

Identifiers with internal linkage can only be accessed inside the current translation unit (inside the current file).

  • Global variables or functions with the static keyword have internal linkage
  • Global constants have internal linkage by default
// Internal linkage (because of `static`)
static int damage = 0;

// Internal linkage (because it's a global constant)
const int MAX_HP = 100;

External linkage

Identifiers with internal linkage can be accessed by other translation units (by other files).

  • Global variables or functions with the extern keyword have external linkage
  • Global variables have external linkage by default
  • Functions have external linkage by default
// External linkage (because it's a global variable)
int number_a = 20;

// External linkage (because of `extern`)
extern int number_b = 20;

// External linkage (because it's a function)
void sayHi() {
  printf("Hello!\n");
}

Using global variables from other files

To actually use global variables with external linkage from other files, you have to use forward declarations.

// fileA.cpp
// Declaration and definition
extern int my_var = 42;
extern const int MY_CONST = 10;
// fileB.cpp
// Forward declaration only
extern int my_var;
extern const int MY_CONST;

References