Interview Preparation topic : About '''extern''' keyword in C/C++
The keyword extern extends the visibility of the variable or the function to the entire program.
By using extern, we can use the variable or function anywhere in the program that may contain one or more files.
For example, consider the below C program with files source1.c and source2.c:
/*************** source1.c **************/
#include <stdio.h>
#include <conio.h>
// Initializing variables var1 and var2
int var1 = 10;
int var2 = 20;
int main()
{
int result;
result = sum();
printf ("%d", result);
return 0;
}
/*************** source2.c **************/
#include <stdio.h>
#include <conio.h>
// Declaring variables var1 and var2
extern int var1;
extern int var2;
// compiler will search for the initialization of the variables var1 and var2
// Since the variables are declared as extern, the compiler will look for the initialization in source1.c and source2.c
int sum()
{
int total;
total = var1 + var2;
return total;
}
It can be used with all data types: int, float, double, char etc. It is default storage class of all global variables and functions.
Below is an example of declaring a variable with and without extern.
Example 1:
#include <stdio.h>
int var; //By default it is extern variable
int main()
{
printf("%d",var);
return 0;
}
Output: 0
Example 2:
#include <stdio.h>
extern int var; //extern variable
int main()
{
printf("%d",var);
return 0;
}
Output: Compilation Error. Undefined symbol var
In example 2, by using extern keyword we have only declared the variable var. So there is no memory allocated for var variable and when we try to access it using printf, we get a compiler error stating undefined symbol. It is necessary to define the variable or allocate memory for extern variable by initializing it as seen below:
Example 3:
#include <stdio.h>
extern int var = 5; //extern variable
int main()
{
printf("%d",var);
return 0;
}
Output: 5
An extern variable can be initialized only globally. We cannot initialize extern variables locally.
Example 4:
#include <stdio.h>
int main()
{
extern int var =10; //Initializing extern variable locally.
printf("%d",i);
return 0;
}
Output: Compilation error: Cannot initialize extern variable.
Example 5:
#include <stdio.h>
int main()
{
extern int var;
int i=10; // Initializing extern variable locally.
printf("%d",var);
return 0;
}
Output: Compilation error: Multiple declaration of variable var.
An extern variable can be declared many times but we can initialize at only one time. For example:
Example 6:
#include <stdio.h>
extern int var;
int var=25; //Initializing the variable
int main()
{
printf("%d",var);
return 0;
}
int var=20; //Initializing the variable
Output: Compilation error: Multiple initialization variable var