Extern Storage Class in C (Keyword)

Extern Storage Class

Extern Storage Class in C

  • The principle use of extern is to specify that a variable is declared with external linkage elsewhere in the program.
  • Extern storage class is used when we have global functions or variables which are shared between two or more files.
  • When Extern specifier is used with a varible declaration them no storage is allocated to that variable and it is assumed that the variable has already been defined elsewhere in the program.
  • When we use extern variable in the main program then initially we need to given them some value. it cannot be blank.
  • We can also use extern variables by importing the customised header file containg all the extern variables.

Use of Extern Storage Class

  • for using extern variables we can create the self customised header file i.e “external.h” and there we have stored int a and int b.
  • In our main file that is named as “prepinsta.c” we can import “external.h” by the following syntax as : #include “external.h”.
  • then we can use the variables declared in the external.h file with initializing again in the prepinsta.c
  • here sum = a + b will show the following output

Output

100 + 200 = 300

external.h

extern int a = 100;
extern int b = 200;

prepinsta.c

#include <stdio.h>
#include "external.h"
int main()
{
int sum = a + b;
printf("%d + %d = %d ", a, b, sum);
return 0;
}

Use of Extern Storage Class in C file.

  • we can use the extern keyword variable in our main program that is named  as “placement.c”.
  • we can declared the extern variables before starting main function.
  • but we also need to give them some value at this stage also.
  • we can change the values of extern variables in the main function as shown in this program.

Output

100 + 200 = 300

placement.c

#include <stdio.h>
extern int a=10;
extern int b=20;
int main()
{
a = 100;
b = 200;
int sum = a + b;
printf("%d + %d = %d ", a, b, sum);
return 0;
}