External Variables in C Programming With Example

External Variable

In the C programming language, an external variable is a variable defined outside any function block. On the other hand, a local (automatic) variable is a variable defined inside a function block.

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.

extern keyword

The extern keyword is used to declare a variable that is defined elsewhere. As with function prototypes, an extern variable declaration doesn't allocate memory. It merely identifies the signature of the variable so that the compiler knows how it should be handled when it is encountered in your code.

Example 1:


 x= 50
 x= 100

See the output, x= 50 is the value of the global variable x and x= 100 is the value of local variable x.

Example 2:

First file: main.c

Second File: Original.c


  value of the external integer is = 98

Read Also,