- External variable
An external variable (keyword extern for C and
C++ programming languages) is avariable 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 thesymbol table of a different translation unit. This is used to expose variables in oneimplementation file to a different implementation file. The external declaration is not resolved by the compiler, but instead by thelinker , 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 reference s (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.
Example ("C")
File 1:
File 2:
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.
External links
* [http://msdn.microsoft.com/en-us/library/2tx32sw2(VS.80).aspx Microsoft C Language Reference: The extern Storage-Class Specifier]
Wikimedia Foundation. 2010.