2.2. Ensuring You Have Only One Instance of a Variable Across Multiple Source Files
Problem
You need the same variable to be used by different modules in a program, and you can only have one copy of this variable. In other words, a global variable.
Solution
Declare and define
the variable in a single implementation file in the usual manner, and use the
extern keyword in other implementation files where
you require access to that variable at runtime. Often, this means including the extern declarations in a header file that is used by all
implementation files that need access to the global variable. Example 2-3 contains a few files that show how
the extern keyword can be used to access variables
defined in another implementation file.
Example 2-3. Using the extern keyword
// global.h
#ifndef GLOBAL_H_ _ // See Recipe 2.0
#define GLOBAL_H_ _
#include <string>
extern int x;
extern std::string s;
#endif
// global.cpp
#include <string>
int x = 7;
std::string s = "Kangaroo";
// main.cpp
#include <iostream>
#include "global.h"
using namespace std;
int main() {
cout << "x = " << x << endl;
cout << "s = " << s << endl;
}Discussion
The extern keyword is a way of telling the compiler
that the actual storage for a variable is allocated somewhere else. extern tells the linker that the variable it qualifies is
somewhere in another object file, and that the linker needs to go find it when creating
the final executable or library. If the linker never finds the extern variable you have declared, or ...