extern

By postponing a variable declaration to the extern specifier, one gives indication to the compiler that the variable is defined elsewhere, either afterwards in the current file or in another file. In the example below, the contents of two different files are reported: externheader.h and externheader.cpp. Notice how the global variable b is defined in externheader.h, which is included into externheader.cpp. The declaration:
extern int b;
indicates that the variable to be used is the one defined in the header file. If the extern keyword were missing, a new, local, variable would be allocated. Further, the declaration:
extern int a;
tells the compiler that the variable definition is yet to be found. In fact, it is located after the main, in the global area.

Example



//externheader.h
int b = 100;

//static int d;
int e;

//externheader.cpp
#include <iostream>
#include "externheader.h"
using namespace std;

int main()
{  
     // the next two statements are declarations which are not definitions
     extern int a;
     extern int b; // defined in another file
     cout << "b's value is: " << b;
     getchar();
     return 0;
}

int a;

Output

b's value is: 100