C++ extern Keyword

The extern keyword in C++ is used to declare a variable or function in another file or scope. It tells the compiler that the variable or function has external linkage, meaning it is defined elsewhere and not within the current file or scope.

It is commonly used in scenarios involving multiple files, where variables or functions need to be shared between files without redefining them.


Syntax

</>
Copy
extern data_type variable_name;

extern return_type function_name(parameter_list);
extern
The keyword used to declare a variable or function with external linkage.
data_type
The type of the variable being declared (e.g., int, float).
variable_name
The name of the variable that is declared but not defined in the current scope.
return_type
The return type of the function declared with extern.
function_name
The name of the function being declared with extern.

Examples

Example 1: Sharing a Variable Between Files

In this example, we will learn how to use the extern keyword to share a variable between two files.

File: variables.cpp

</>
Copy
#include <iostream>
using namespace std;

int sharedVariable = 42; // Define the variable

File: main.cpp

</>
Copy
#include <iostream>
using namespace std;

extern int sharedVariable; // Declare the variable

int main() {
    cout << "Shared variable: " << sharedVariable << endl;
    return 0;
}

Output:

Shared variable: 42

Explanation:

  1. The variable sharedVariable is defined in variables.cpp.
  2. In main.cpp, the variable is declared with the extern keyword, allowing it to be accessed.
  3. The value of sharedVariable is printed in the main function.

Example 2: Using extern for Functions

This example shows how to use the extern keyword to declare and use a function defined in another file.

File: functions.cpp

</>
Copy
#include <iostream>
using namespace std;

void printMessage() {
    cout << "Hello from another file!" << endl;
}

File: main.cpp

</>
Copy
#include <iostream>
using namespace std;

extern void printMessage(); // Declare the function

int main() {
    printMessage(); // Call the function
    return 0;
}

Output:

Hello from another file!

Explanation:

  1. The function printMessage is defined in functions.cpp.
  2. In main.cpp, the function is declared with the extern keyword.
  3. The printMessage function is successfully called from main.cpp.

Key Points about extern Keyword

  1. The extern keyword allows variables or functions to be shared across multiple files.
  2. It declares that a variable or function has external linkage and is defined elsewhere.
  3. The extern keyword does not allocate storage for a variable—it only declares its existence.
  4. For global variables and functions, the extern keyword is not mandatory if the #include directive is used to include the definition.
  5. Using extern can help in modular programming by separating definitions and declarations across files.