External variable
From Wikipedia, the free encyclopedia
In computer programming, an external variable is a variable that is declared outside any function. Contrary to popular belief, this does not necessarily make the variable global. In programming languages such as C and C++, the scope of an external variable begins at its point of declaration, and ends at the end of its module, or source file.
If a function must access an external variable, but is outside the variable's scope, then the function must redeclare the variable within itself using the keyword extern.
int main () { //Redeclaring external variables before use extern int v_Integer; extern char v_CharArray []; } //Declaring variables int v_Integer; char v_CharArray [3]; void f_one() { v_Integer = 4; v_CharArray = {"a", "b", "c"}; }
In the above example, the function "main" must redeclare the v_Integer and v_CharArray as external before it can access them, whereas the function "f_one" must not. This is because the variables were declared after the definition of "main", and so "f_one" is within their scope, but "main" is not. Also, the array "v_CharArray" was redeclared within the function "main". However, the redeclaration did not include the array size. This is because when redeclaring external variables you're not allocating memory - it has already been allocated. You're only declaring the property of the variable.
It should be noted that because the scope of an external variable ends at the end of the source file within which it was declared, then any function defined within another source file must redeclare the external variable before use.