有以下文件:
share.h/cppmain.h/cpp
若需要在main.cpp中使用share.h中定义的全局变量int a,则需要满足:
share.h为extern int a;- 不能在
.h中定义变量值
- 不能在
share.cpp定义a的值int a=5;
- 在
main.h中include文件share.h

static与extern的区别
新手非常容易出现的误区:像Java一样使用static定义全局变量
用static在.h文件中定义值,虽然可以编译过,但是该变量是无法多文件共享的,只能在*/h.cpp共享。有多少个.h/cpp使用了定义了static的.h就会有多少个同名static变量,并且为0。