

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
- Related Questions & Answers
- What is an extern storage class in C language?
- The auto storage class in C++
- The register storage class in C++
- The static storage class in C++
- The mutable storage class in C++
- “extern” keyword in C
- What is an auto storage class in C language?
- What is a static storage class in C language?
- What is a register storage class in C language?
- When to use extern in C/C++
- What is the effect of extern “C” in C++?
- Volatile Storage vs Non-Volatile Storage
- Name Mangling and extern “C” in C++
- Storage Management
- Difference between Session Storage and Local Storage in HTML5