External Storage Class in C Programming

This storage class is also used for global variables. It also acts like a static variable. But its scope is extended to other files of the same programs too. That means, we can have multiple related files being executed when a program is executed. If any variables are to be used just like static variable above in the functions that are present different files, then we declare the variable as extern. This variable is also stored in the RAM memory and is automatically initialized to zero when it is declared in the block or function.

Consider a program which has two files – one for having main function and in another file it keeps track of number of times the function is being called. Let main function file be exterExample.c and other file be calcCounter.c

// exterExample.c
#include <stdio.h>

int intTotal;
extern void calcCount ();

void main (){
  // Initial value of intTotal cannot be displayed here since it is declared in other file and is not yet 
called

  	calcCount ();
	printf ("\nValue at intTotal after calling the function is %d ", intTotal);
	calcCount ();
	printf ("\nValue at intTotal after the 2nd call to function is %d ", intTotal);

Here we have two files as discussed earlier. The first file contains the main function; hence program begins executing from that file. Hence we need to declare all the functions and variables being used. We have declared intTotal as normal global variable because it is going to be printed in the main function. But the same is going to be used in the other file also. Hence it should be a global variable. But it is not  static here. We have declared the function calcCount () as extern to indicate the compiler that it a function written in other file and needs to be called in this file. In other words, extern is the only keyword which allows variables and functions to be used across the files. Now we call that function as if it is in the same file.

The second file calcCounter.c contains an extern variable, which indicates the compiler that it is a global variable from other file and its value needs to be used in this file. Since it is declared as extern, it initializes the value to zero when the calcCount () function is called for the first time. In this function it increments the value of intTotal by 1. Hence it prints the value as 1 in the main function. It retains the value of intTotal in both the files, since it is declared as extern. When the function is called second time, it comes to the second file, and it still keeps the value of intTotal as 1. This is because intTotal is extern and has been already initialized to zero when program started. It again increments the value of intTotal and displays its value as 2 in the main function. This is how extern is used as global variable across the files to retain its value.

Translate »