The extern
keyword in C++ is used to declare a variable or function that is defined in another translation unit.
This is particularly useful when working with global variables and functions that need to be accessed across multiple files.
extern
with VariablesThe following simple program shows the extern
keyword in action:
// globals.cpp
int GlobalVar{42};
// main.cpp
#include <iostream>
extern int GlobalVar;
int main() {
std::cout << "GlobalVar: " << GlobalVar;
}
GlobalVar: 42
globals.cpp
, GlobalVar
is defined.main.cpp
, extern int GlobalVar;
declares that GlobalVar
exists and will be defined elsewhere.GlobalVar
to be used in main.cpp
without defining it there.extern
with FunctionsHere’s an example with an extern
 function:
// greeting.cpp
#include <iostream>
void SayHello() {
std::cout << "Hello from greeting\n";
}
// main.cpp
#include <iostream>
extern void SayHello();
int main() {
SayHello();
}
greeting.cpp
, SayHello()
is defined.main.cpp
, extern void SayHello();
declares that SayHello()
exists elsewhere.SayHello()
to be called in main.cpp
.extern
extern
are only defined once across the entire program.extern
declaration must match the definition in terms of type and qualifiers.extern
ConstantsThe extern
keyword can be combined with other qualifiers, such as const
:
// math.cpp
extern const float Pi{3.14159f};
// main.cpp
#include <iostream>
extern const float Pi;
int main() {
std::cout << "Pi: " << Pi;
}
Pi: 3.14159
In this case, Pi
is a const
variable with extern
linkage. The extern
keyword allows its use in main.cpp
, even though it is defined in math.cpp
.
The extern
keyword is essential for managing linkage and ensuring variables and functions can be accessed across multiple files, promoting a modular and organized code structure.
Answers to questions are automatically generated and may not have been reviewed.
A deeper look at the C++ linker and how it interacts with our variables and functions. We also cover how we can change those interactions, using the extern
and inline
keywords