我们知道,如果否则将全局变量定义在头文件中,然后又在多处include该头文件,会导致全局变量的重复定义,从而无法编译:
//b.h #ifndef B_H_ #define B_H_ int c_data = 100; //在头文件b.h中定义了全局变量c_data void fun_b(); #endif //-------------------------------------------------------------------- //b.cpp #include#include "b.h" //导入b.h导致c_data被定义 using namespace std; void fun_b() { cout< #include "b.h" //导入b.h导致c_data被定义 using namespace std; int main () { fun_b(); return 0; } 由于b.cpp和main.cpp都include了头文件b.h,相当于c_data被定义了两遍 因此导致编译器报错:multiple definition of `c_data'
解决方案是:
在cpp文件中定义全局变量,然后再头文件中对其声明:
//b.h #ifndef B_H_ #define B_H_ extern int c_data; //在头文件中声明全局变量 void fun_b(); #endif //--------------------------------------------------------------------------- //b.cpp #include#include "b.h" using namespace std; int c_data = 100; //在cpp文件中定义全局变量 void fun_b() { cout< #include "b.h" using namespace std; int main () { fun_b(); return 0; }
这一规则有一个例外:如果这个全局变量是const型的,那么可以在头文件中对其进行定义,且不会导致重复定义:
//b.h #ifndef B_H_ #define B_H_ const int c_data = 100; //在头文件中定义全局const变量 void fun_b(); #endif //--------------------------------------------------------------------------- //b.cpp #include#include "b.h" using namespace std; void fun_b() { cout<<"in b.cpp "< #include "b.h" using namespace std; int main () { fun_b(); cout<<"in main.cpp "< 事实上,上面的程序之所以能成功编译,是因为对于const全局变量,C++会默认认为其为内部连接,除非将其声明为外部连接:
#ifndef B_H_ #define B_H_ const int c_data = 100; //将c_data声明为外部连接的全局const变量 void fun_b(); #endif 由于c_data被声明为外部连接,因此不能被多次include到不同的cpp文件,否则编译器会报重复定义 具有外部连接的const全局变量跟普通全局变量一样,需要在cpp文件中定义,并在h文件中对其声明



