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 ...READ MORE
Jun 21, 2022
in C++
by
Damon
• 4,960 points
•
2,422 views