Using the extern Keyword
Can you give more examples of when to use the extern keyword?
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.
Example of extern with Variables
The 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: 42Explanation
- In
globals.cpp,GlobalVaris defined. - In
main.cpp,extern int GlobalVar;declares thatGlobalVarexists and will be defined elsewhere. - This allows
GlobalVarto be used inmain.cppwithout defining it there.
Example of extern with Functions
Here'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();
}Explanation
- In
greeting.cpp,SayHello()is defined. - In
main.cpp,extern void SayHello();declares thatSayHello()exists elsewhere. - This allows
SayHello()to be called inmain.cpp.
Benefits of extern
- Code Organization: It helps keep code modular and organized by allowing definitions to be separated from declarations.
- Global Variables: Facilitates the use of global variables across different files without redefining them.
Common Mistakes
- Multiple Definitions: Ensure variables defined with
externare only defined once across the entire program. - Matching Declarations: The
externdeclaration must match the definition in terms of type and qualifiers.
Example of extern Constants
The 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.14159In 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.
Internal and External Linkage
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