变量的定义与声明
| 12
 3
 4
 
 | extern int a;       int a;
 extern int a = 0;
 int a = 0;
 
 | 
- 定义只能有1处,但声明可以有多处
- 定义引起内存分配,声明则不会
- 注意变量和函数的声明默认就是 extern
函数的定义与声明
函数的定义和声明是有区别的,定义函数要有函数体,声明函数没有函数体,所以函数定义和声明时都可以将 extern 省略掉
头文件中的全局变量
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 
 | #ifndef _TEST_H_
 #define _TEST_H_
 
 
 static int a = 0;
 
 
 
 const int b = 1;
 
 
 
 
 
 extern int c;
 
 
 
 
 extern int d = 0;
 
 
 
 const std::vector<std::string> VN_MULTICELLTYPE = {"1", "2"};
 #endif
 
 | 
- 注意全局 const 默认为该编译单元的局部变量(内部链接性),即类似 static 修饰(C 和 C++ 不同,const 常量在 C 中依旧是外部链接性的 )
- 在头文件中定义 static/const 变量会造成变量多次定义,造成内存空间的浪费,而且也不是真正的全局变量。应该避免使用这种定义方式
- 正确的方式是在头文件中使用声明,在某一个实现文件中定义,其他实现文件引用即可
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | #ifndef _TEST_H_
 #define _TEST_H_
 extern int a;
 #endif
 
 
 #include "test.h"
 a = 2;
 cout << a << endl;
 
 
 #include "test.h"
 cout << a << endl;
 
 | 
参考文章