We have seen what is meant by definition and declaration of a variable. In short, declaration of a variable indicates to the compiler the presence of a variable in the source whereas definition indicates that memory has been allocated to a variable.
Variables which have been defined inside a function are automatic and have scope limited to that particular function. A global variable is one which is defined outside the scope of any function. Rather the scope of the global variable is the entire program.
int gbl; /* Global variable */
int foo()
{
int a = 100; /* local(automatic) variable */
gbl = 10;
return a;
}
int main()
{
int b; /* local(automatic) variable */
gbl = 20;
foo();
printf("gbl = %d", gbl); /* gbl = 10 */
return;
}
The concept of external variables comes from the fact that a C program is a collection of files with each file consisting of a module. So if we want to call a function from one module to another, the other module should know about the definition of the function. We use the “extern” keyword and the declaration of the variable to tell the compiler that it exists elsewhere and we want to use it in this particular module.
File 1
int gbl; /* Global variable */
int foo() /* Global function */
{
int a = 100;
gbl = 10;
return a;
}
File 2
extern int gbl; /* Declaration of an external variable */
extern int foo(); /* Declaration of an external function */
int main()
{
extern int gbl; /* Declaration of external variable gbl again with no problem.
If "extern" is not used here, it becomes local*/
int b = 200;
foo();
gbl = 20;
return 0;
}
An external variable should be defined at only one place but it can be declared any number of times. By default, all C functions are external as they are all global and can be called from any module.
Ideally using too many global variables should be avoided in any C program. This is so that we can have minimum interaction between the program modules(something called as coupling). But if we are to use global external variables, it is best to place them in a header file and include the header in whichever modules want to use them.

