External linkage doesn't work

Pages: 12
Note that linkage doesn't only apply to variables but also to types, functions, templates, etc. If nothing had external linkage there would be no way for a translation unit to use something that has been defined in another translation unit so you would be forced to only use one single translation unit for the whole program.

The rules for variables is actually very similar to that of functions. Both have external linkage by default and the definition is only allowed inside one translation unit. Before the function or variable can be used inside a translation unit it needs to be declared. When you write a function and leave out the function body it is clear to the compiler that it's only a function declaration. With variables there is nothing you can leave out to make it only a declaration so that is why you have to use the extern keyword. You can use extern with function declarations too but it is not necessary.
Last edited on
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...
Topic archived. No new replies allowed.
Pages: 12