Extern Storage Class in C (Keyword)

Extern Storage Class in C

Extern is mostly used to indicate that a variable has been defined with external linking in another part of the program.

When we have global variables or methods that are shared by two or more files, we use an external storage class.

No storage is allocated to a variable when the extern specifier is used with a variable declaration since it is presumed that the variable has already been created elsewhere in the program.

Extern Storage Class

Use of Extern Storage Class

  • We can construct the self-customized header file “external.h” for using extern variables, and there we have stored int a and int b.
  • The syntax for importing “external.h” into our main “prepinsta.c” code is as follows: #include “external.h”.
  • The variables declared in the external.h file can then be used after being initialised once more in the prepinsta.c file.
  • Here sum = a + b will show the following output

Example 1

File name: external.h
int a = 100;
int b = 200;
File name: prepinsta.c
Run
#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
Run
#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

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription