分爲3步:
1.在A.cpp 中聲明:
extern int a;
2.在A.cpp【注意和上面A.h對應】中定義:
int a;
或
int a=0;\
3.在其他源文件中直接訪問即可
c.cpp中:
a=10;
如果在A.h中定義 int a;在b.cpp和c.cpp中include “A.h" 會報重定義的錯
如果在A.h中定義 extern int a=10;在b.cpp和c.cpp中include “A.h" 也會報重定義的錯
如果在A.h中定義 static int a=10;在b.cpp和c.cpp中include “A.h",不報錯,但b.cpp和a.cpp中的a是2個獨立的a
如果在.cpp裏使用static定義,則該變量只在當前cpp文件中有效,在別的文件中無效
在.h裏使用static定義,不會進行編譯(.h文件不編譯),只會在其每個include的cpp文件中包含編譯,相當於在.cpp裏使用static定義。