Table of contents
In C++, extern is a very important keyword, which is used to declare a variable or function that is defined in another file. In this article, we will introduce the use of extern in detail and provide some practical application scenarios.
What is extern?
extern is a keyword used to tell the compiler that a variable or function is defined in another file. It can be used in two situations:
- Declare a global variable or function for use in other files.
- Reference global variables or functions defined in other files in the current file.
How to use extern?
Declare a global variable or function
Suppose we have two files: main.cpp and helper.cpp. We want to use global variables and functions defined in helper.cpp in main.cpp. For this, we need to declare these variables and functions using extern keyword in main.cpp.
// helper.h
extern int global_variable;
extern void helper_function() ;
// helper.cpp
int global_variable = 42;
void helper_function() {
// do something
}
// main.cpp
extern int global_variable;
extern void helper_function();
int main() {
// use global_variable and helper_function
printf("%d", global_variable);
helper_function();
return 0;
}
Reference global variables or functions defined in other files in the current file
Suppose we have two files: main.cpp and helper.cpp. We want to use global variables and functions defined in main.cpp in helper.cpp. For this, we need to declare these variables and functions using extern keyword in main.cpp and use them in helper.cpp.
// main.cpp
extern int global_variable;
void main_function() {
// do something
}
// helper.cpp
extern int global_variable;
extern void main_function();
void helper_function() {
// use global_variable and main_function
}
Application scenarios
extern is often used in large projects where the code is divided into multiple files. It allows defining variables or functions in one file and using them in other files. This way we can better organize the code and make it easier to maintain.
For example, in a game project, we might have one file to handle user input, another file to handle game logic, and yet another file to handle graphics rendering. Using extern, we can share variables and functions between these files, making the code more modular and manageable.
expand
Combining atomic variables to implement multi-threaded operations
Define atomic variables in the header file
cpp file initialization
Multi-threaded use
Declaring variables in the header file
Multi-threaded concurrent use
in conclusion
In C++, extern is a very useful keyword for sharing variables and functions between multiple files. It can make the code more modular and easier to manage. When using extern, make sure to declare variables and functions correctly and use them when needed.