Extern Storage Class in C (Keyword)

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 variable declaration then no storage is allocated to that variable and it is assumed that the variable has already been defined elsewhere in the program.

Extern Storage Class

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
File name: external.h
int a = 100;
int b = 200;
File name: prepinsta.c
#include <stdio.h>
#include "external.h"
int main()
{
  extern int a,b;
  int sum = a + b;
  printf("%d + %d = %d ", a, b, sum);
  return 0;
}
Output
100 + 200 = 300

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 declare 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.
File name: 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;
}
Output
100 + 200 = 300