External variable

From Wikipedia, the free encyclopedia

An external variable (keyword extern for C and C++ programming languages) is a variable declaration keyword used to signify that a global variable has been declared in another file, and is simply used within the file containing the extern keyword. There are two specific meanings to extern, which are dependent on context.

When applied to the declaration of a variable, extern tells the compiler that said variable will be found in the symbol table of a different translation unit. This is used to expose variables in one implementation file to a different implementation file. The external declaration is not resolved by the compiler, but instead by the linker, meaning that extern is a legitimate mechanism to install modularity at the compiler level.

When applied to the instantiation of a variable, extern promotes that variable into the symbol table of the translation unit, therefore the symbol may be referenced from other translation units. There must be a single implementation of the variable somewhere, marked extern (typically in the header,) for other translation units to refer to the variable.

Two important uses of externality are common: preventing circular references (in a fashion similar to the section declarations of languages like Pascal) and preventing compiled dependency chains.

External variables may be declared outside any function block in a source code file the same way any other variable is declared: by specifying its type and name. No storage class specifier is used - the position of the declaration within the file indicates external storage class. Memory for such variables is allocated when the program begins execution, and remains allocated until the program terminates. For most C implementations, every byte of memory allocated for an external variable is initialized to zero.

The scope of external variables is global, i.e. the entire source code in the file following the declarations. All functions following the declaration may access the external variable by using its name. However, if a local variable having the same name is declared within a function, references to the name access the local variable cell.

[edit] Example

File 1:

 int GlobalVariable; // definition
 main () {
   GlobalVariable = 1;
   void SomeFunction (void);
 }

File 2:

 extern int GlobalVariable;  // declaration
 void SomeFunction (void){   
   GlobalVariable++;
 }

In this example the variable GlobalVariable is defined in File 1. In order to utilize the same variable in File 2, it must be declared using the extern keyword. Regardless of the number of files, a global variable is only defined once, however, it must be declared using extern in any file outside of the one containing the definition. Technically, SomeFunction is also external, but in C and C++ all functions are considered external by default and usually do not need to be declared.

[edit] References:

An article on external variables