C++ extern keywords
Created By: chatGPT
C++
extern
is a storage class specifier that is used to declare a variable or function and indicate that it has external linkage. This means the variable or function can be accessed across different translation units. Using extern
, we can share variables between multiple files. Notice that extern
does not allocate memory for the variable; it merely provides a reference to it. Here’s an example: // File1.cpp
int globalVar = 10; // Definition of globalVar
// File2.cpp
extern int globalVar; // Declaration of globalVar
void printGlobalVar() {
std::cout << "Global Variable: " << globalVar << std::endl;
}
In the example above, we define
globalVar
in File1.cpp
, and then declare it in File2.cpp
using extern
. This allows File2.cpp
to access the globalVar
defined in File1.cpp
. It’s crucial to ensure that the actual definition is present in one of the files, or linking will fail due to an unresolved reference. // File1.cpp
#include <iostream>
int globalVar = 10; // Definition of globalVar
int main() {
std::cout << "From File1: " << globalVar << std::endl;
return 0;
}
// File2.cpp
#include <iostream>
extern int globalVar; // Declaration of globalVar
void printGlobalVar() {
std::cout << "From File2: " << globalVar << std::endl;
}
If we want to declare functions as extern, we use a similar approach. Declaring a function as
extern
allows it to be called from other files. Here’s an example: // FileA.cpp
#include <iostream>
extern void displayMessage(); // Declaration of the function
int main() {
displayMessage(); // Calling the extern function
return 0;
}
// FileB.cpp
#include <iostream>
void displayMessage() {
std::cout << "Hello from FileB!" << std::endl;
}
In this example,
displayMessage
is declared in FileA.cpp
using extern
, and its definition exists in FileB.cpp
. When FileA.cpp
is compiled and linked with FileB.cpp
, calling displayMessage()
from FileA
works seamlessly.// FileA.cpp
#include <iostream>
extern void displayMessage(); // Declaration of function
int main() {
displayMessage(); // Calling the extern function
return 0;
}
// FileB.cpp
#include <iostream>
void displayMessage() {
std::cout << "Hello from FileB!" << std::endl;
}