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:
- The variable
sharedVariable
is defined invariables.cpp
. - In
main.cpp
, the variable is declared with theextern
keyword, allowing it to be accessed. - The value of
sharedVariable
is printed in themain
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:
- The function
printMessage
is defined infunctions.cpp
. - In
main.cpp
, the function is declared with theextern
keyword. - The
printMessage
function is successfully called frommain.cpp
.
Key Points about extern
Keyword
- The
extern
keyword allows variables or functions to be shared across multiple files. - It declares that a variable or function has external linkage and is defined elsewhere.
- The
extern
keyword does not allocate storage for a variable—it only declares its existence. - For global variables and functions, the
extern
keyword is not mandatory if the#include
directive is used to include the definition. - Using
extern
can help in modular programming by separating definitions and declarations across files.