This is useful when dealing with global variables.
Global variables are declared in a header so that any source file that contains the header is aware of them, but you only need to "define" them once in one of your source files.
To explain, using extern int x; informs the compiler that an int object named x exists elsewhere.
It is not the compiler's responsibility to know where it exists; it just needs to know the type and name so that it may utilise it.
After compiling all of the source files, the linker will resolve all x references to the one definition found in one of the generated source files.
For it to operate, the x variable's declaration must have "external linkage," which simply means that it must be defined outside of a function (at what's known as "the file scope") and without the static keyword.
header:
#ifndef HEADER_H
#define HEADER_H
// any source file that includes this will be able to use "global_x"
extern int global_x;
void print_global_x();
#endif
source 1:
#include "header.h"
// since global_x still needs to be defined somewhere,
// we define it (for example) in this source file
int global_x;
int main()
{
//set global_x here:
global_x = 5;
print_global_x();
}
source 2:
#include <iostream>
#include "header.h"
void print_global_x()
{
//print global_x here:
std::cout << global_x << std::endl;
}