What is the method for declaring and defining extern in C++?
In C++, the extern keyword is used to reference global variables, functions, or objects defined in another file. By using the extern keyword, the compiler is informed that the definition of the variable, function, or object is in a different file rather than the current one.
There are two ways to declare extern.
- Declare a variable: Declare a global variable in one file where its definition is in another file. For example:
extern int globalVariable; // 声明一个全局变量,定义在其他文件中
- Reference a function or object: Declare a function or object in one file, with its definition in another file. For example:
extern void function(); // 声明一个函数,定义在其他文件中
extern MyClass object; // 声明一个对象,定义在其他文件中
The correct way to use the extern declaration is to declare in one file and define in another. For example, if a global variable is declared in one file, it should be defined in another file.
// File1.cpp
extern int globalVariable; // 声明全局变量
// File2.cpp
int globalVariable = 10; // 定义全局变量
Note: The extern keyword simply indicates that the variable, function, or object is defined in another file, and it is not necessary to use the extern keyword for declaration. Sometimes in C++, it is possible to define directly in a file without the need for the extern keyword for declaration. In this case, the compiler will consider the variable, function, or object definition as global.