It helps to note the difference between a variables
definition and its
declaration. The definition of a variable causes the compiler to allocate space for it. There can be only 1
definition of any variable. The
declaration tells the compiler what type the variable is (int, string, double etc) but does not allocate space. You can
declare a variable as many times as you want, in as many compilation units as you like:
1 2
|
int var; // This is a definition.
extern int var; // This is a declaration.
|
As you see, adding "extern" changes a definition into a declaration.
Going back to the C days,
extern
is a way to tell the compiler about a variable whose definition is
external to the current compilation unit.
Because you can have only 1 definition of a variable in a program, it's almost always a bad idea to put a definition in a header file. If two compilation units include the header file then you'll have multiple definitions of the variable and that's an error. Header files should contain declarations only.
As for the merits of global variables, if you believe that globals are horrible evil things that should never be used, then you should stop using
std::cin
and
std::cout
immediately...