The keyword extern is used to declare a variable or function as an external variable or an external function, that is, to tell the compiler that it is defined in other files, not to give an error when compiling, and to find the variable or function by the time the link is addressed by the string. (The function defaults to the external type and does not need to display the declaration, but the variable must, if you want to declare a function to be valid only in the scope of this file, you can use static to illustrate)
In a header file, for example, if a global variable such as int A is defined in A.h, then the function in the other file calls the variable A to declare it in the corresponding header file or in the definition file (guaranteed to use extern int a before using the variable), but there is a disadvantage in doing so. First, if a large number of global variables are defined in the A.h for use by other files, a large number of extern * * * statements are repeated in other call files, and second, if other files refer directly to A.h, it will result in a duplicate definition of global variables, compile, and so on. In order to avoid the above problems, summed up the use of the following extern code, the contents are as follows:
1. Define global variables in the definition file, such as global variable int a in A.cpp;
2. Declare the external variable extern int A in the corresponding header file A.h;
3, in the reference to a variable file contains A.h;
(Original link: http://soartomato.iteye.com/blog/902778)
Add:
1. Extern This keyword compares the egg to ache, in the declaration time, the extern actually can be omitted, therefore will let you not be able to understand in the end is the declaration or the definition.
extern int A; Statement A
int A; may be a declaration or a definition
int a = 0; Define a and assign an initial value
2. Definitely do not define variables in the header file, otherwise it is very easy to cause errors, #ifndef ... #endif will help you prevent header files from being duplicated and avoid compilation errors.
But if multiple. C file refers to this variable, it will cause a link error (such as: multiple definition of ' a ').