What is Extern Variable



Extern:
In the C programming language, an external variable is a variable defined outside any function block. External variables are allocated and initialized when the program starts, and the memory is only released when the program ends. Their lifetime is the same as the program's.
Let us try to understand extern with examples.
Example 1:
int var;
int main(void)
{
   var = 10;
   return 0;
}
Analysis: This program is compiled successfully. Here var is defined (and declared implicitly) globally.
Example 2:
extern int var;
int main(void)
{
  return 0;
}
Analysis: This program is compiled successfully. Here var is declared only. Notice var is never used so no problems.
Example 3:
extern int var;
int main(void)
{
 var = 10;
 return 0;
}
Analysis: This program throws error in compilation. Because var is declared but not defined anywhere. Essentially, the var isn’t allocated any memory. And the program is trying to change the value to 10 of a variable that doesn’t exist at all.
Example 4:
#include "somefile.h"
extern int var;
int main(void)
{
 var = 10;
 return 0;
}
Analysis: Supposing that somefile.h has the definition of var. This program will be compiled successfully.
Example 5:
extern int var = 0;
int main(void)
{
 var = 10;
 return 0;
}
Extern variable : Best way to declare and define global variables
Although there are other ways of doing it, the clean, reliable way to declare and define global variables is to use a header file file3.h to contain an extern declaration of the variable. The header is included by the one source file that defines the variable and by all the source files that reference the variable. For each program, one source file (and only one source file) defines the variable. Similarly, one header file (and only one header file) should declare the variable.
file3.h
extern int global_variable;  /* Declaration of the variable */
file1.c
#include "file3.h"  /* Declaration made available here */

/* Variable defined here */
int global_variable = 37;    /* Definition checked against declaration */

int increment(void) { return global_variable++; }
file2.c
#include "file3.h"
#include <stdio.h>

void use_it(void)
{
    printf("Global variable: %d\n", global_variable++);
}

No comments:

Post a Comment