Keyword "extern"

Suppose we have a large project in which we are using several source code files. There may be global variables declared in one of the files which we want to use in other files. (You might say we want them to be "super-global".)

For example, in FileA, we have

     char * Phrase = "Shazam";

and we would like to use Phrase in FileB. Unfortunately, the compiler will complain in FileB that it has never heard of Phrase.

One notion would be to repeat the declaration of Phrase in FileB. This would get past the compiler, but it has introduces two problems:

The solution to this is that we use extern. In FileB, we have

     extern char * Phrase;

which informs the compiler and linker that there is a variable of this type and name declared elsewhere.

That is to say, we have an ordinary variable declaration for Phrase inFileA (including initialization, if we want) and a second declaration for Phrase using "extern" in FileB (not initializing it). The memory for Phrase is allocated and initialized when FileA is compiled.

This is all right if we have just two source code files, but we might have many of them, all using Phrase. In that case, we would have to have

     extern char * Phrase;

listed in all of them except FileA. Again, this could be a headache later if, for instance, we want to change it from char to wchar.

For that reason, the proper way to handle this is to put the extern declaration of Phrase in a header file and #include that header file in each and every source code file (with appropriate header guards). If we later need to make changes, we only have to worry about changes to FileA and to the header file.

It might be a good idea to document in the header file the fact that FileA contains the real declaration and in FileA that the extern statement is in that specific header file.

One way to think of "extern" is that we are providing a kind of prototype statement for a variable. ("Here it is; use it; take my word for it that it has been declared properly somewhere else.")