The extern storage class in C++


The extern storage class specifier lets you declare objects that several source files can use. An extern declaration makes the described variable usable by the succeeding part of the current source file. This declaration does not replace the definition. The declaration is used to describe the variable that is externally defined.

An extern declaration can appear outside a function or at the beginning of a block. If the declaration describes a function or appears outside of a function and describes an object with external linkage, the keyword extern is optional.

If a declaration for an identifier already exists at file scope, any extern declaration of the same identifier found within a block refers to that same object. If no other declaration for the identifier exists at file scope, the identifier has external linkage.

C++ restricts the use of the extern storage class specifier to the names of objects or functions. Using the extern specifier with type declarations is illegal. An extern declaration cannot appear in class scope.

You can use the extern keyword as follows to share the variable across files −

file3.h

extern int global_variable;  /* Declaration of the variable */

file1.c

#include "file3.h"  /* Declaration made available here */
#include "prog1.h"  /* Function declarations */
/* Variable defined here */
int global_variable = 37;    /* Definition checked against declaration */

int increment(void) {
   return global_variable++;
}

file2.c

#include "file3.h"
#include "prog1.h"
#include <stdio.h>

void use_it(void)
{
   printf("Global variable: %d\n", global_variable++);
}

The following question at stackoverflow completely captures the essence of the extern keyword: https://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files.


Updated on: 10-Feb-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements