External Variable - Example (C Programming Language)

Example (C Programming Language)

File 1:

int GlobalVariable; // implicit definition void SomeFunction(void); // function prototype (declaration) int main { GlobalVariable = 1; SomeFunction; return 0; }

File 2:

extern int GlobalVariable; // explicit declaration void SomeFunction(void) { // function header (definition) ++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. Regardless of the number of files, a global variable is only defined once, however, it must be declared in any file outside of the one containing the definition.

If the program is in several source files, and a variable is defined in file1 and used in file2 and file3, then extern declarations are needed in file2 and file3 to connect the occurrences of the variable. The usual practice is to collect extern declarations of variables and functions in a separate file, historically called a header, that is included by #include at the front of each source file. The suffix .h is conventional for header names.

The C Programming Language

Read more about this topic:  External Variable

Famous quotes containing the word programming:

    If there is a price to pay for the privilege of spending the early years of child rearing in the driver’s seat, it is our reluctance, our inability, to tolerate being demoted to the backseat. Spurred by our success in programming our children during the preschool years, we may find it difficult to forgo in later states the level of control that once afforded us so much satisfaction.
    Melinda M. Marshall (20th century)