(i) extern in the header file usage
Because the header file is contained in more than one source file, and the definition of the variable can only occur once, in the header file, you can only declare that no definition can occur. We can declare global variables in the header file with extern, so that the declared global variable (such as variable A in the following program) can be used directly in the CPP containing this header file.
But there are three exceptions:
1. Class can be defined in the header file
2. Const object that value is known at compile time
3. You can define the inline function
extern int ival; Yesextern int ival=1; Errorint ival; errorconst int ival = 3; Yes
(ii) Use of head file protectors to avoid multiple inclusions
#ifndef detects if the specified preprocessor variable is undefined, #define接受一个名字并定义改名字为预处理器变量. #endif代表处理的边界.
mine.h#include <iostream>extern int a;const int b = 2;//int C; Error hint repeating definition//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 (if local cannot be used in another CPP) int main () {cout << a << "" << b << endl;return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C + + Primer learning notes and thinking _3---header files those things (extern)