(i) extern in the header file use method
Because header files are included in multiple source files. And the definition of the variable can only occur once, so in the header file. It is only possible to declare that a definition cannot occur.
We can declare global variables in the header file with extern so that the declared global variable can be used directly in the CPP including this header file (for example, variable A in the following program).
But there are three exceptions:
1. Can define class in header file
2. Const object that value is known at compile time
3. Ability to define inline functions
extern int ival; Yesextern int ival=1; Errorint ival; errorconst int ival = 3; Yes
(ii) Use of head file protectors to avoid multiple including
#ifndef detects if the specified preprocessor variable is undefined. #define接受一个名字并定义改名字为预处理器变量.
#endif代表处理的边界.
mine.h#include <iostream>extern int a;const int b = 2;//int C; The error hint repeatedly defines//hello.cpp#include "mine.h" int f (int x) {return a++;} Amin.cpp#ifndef Test//detects if the specified preprocessor variable does not define a # define TEST//definition preprocessor variable # include "Mine.h" #endif //endusing namespace std ; int a = 2; extern is for global variables (assuming local cannot be used in a CPP) int main () {cout << a << "" << b << endl;return 0;}
C + + Primer learning notes and thinking _3---header files those things (extern)