C++ extern浅析
extern是外部声明关键字,字面意思就是声明某种变量或函数,在外部定义。
extern声明变量的两种方法
1.在其他文件中直接extern
2.在源文件中定义,头文件中使用extern声明,然后使用其他文件直接包含头文件
1 /* test.h */ 2 3 #ifndef_TEST_H_ 4 #define_TEST_H_ 5 6 extern int a; 7 8 #endif
1 #include<iostream> 2 #include"test.h" 3 using namespace std; 4 int a = 0;
注意:以下是错误示范,编译器会报错显示变量a被重定义
有两个源文件包含了头文件,编译阶段会因为两次定义变量a而报错。