C External Variables and Functions
Description
To use a global variable that's defined in another file, declare the variable as external to the current file using the extern keyword.
Syntax
extern type variableName;
Example
For example, we have the following two variables defined in another file as global using the statements. Those declarations are outside of any of the functions.
int myInt = 0;
double myDouble = 2.54;
then in a function in which we want to access these variables, we can specify that these variable names are external by using these statements:
extern int myInt;
extern double myDouble;
These statements don't create these variables. They just identify to the compiler that these names are defined elsewhere.
Note
The variables specified as extern must be declared and defined somewhere else in the program, usually in another source file.
Only one declaration of each global variable is allowed in a file. The global variables may be declared as external in as many files as necessary.
To make the external variables accessible to all functions within the current file, declare them as external at the very beginning of the file, prior to any of the function definitions.
We can place all initialized global variables to one file and all the extern statements in a header file. The extern statements can be incorporated into any program file by using an include statement.