c++中函数默认就是全局的, 变量写在函数外的话默认也是全局的.
Global.cpp , 定义一个全局变量和一个全局函数
- #include <iostream>
- using namespace std;
- int g_int = 10;
- void globalMethod()
- {
- cout << "globalMethod()" << '\n';
- }
全局函数的声明需要使用extern关键字, 以告诉编译器, 这是在其它地方定义了的变量或函数.
Main.cpp
- #include <iostream>
- using namespace std;
- extern int g_int; // 全局变量的声明, 一定要加上extern才行
- extern void globalMethod(); // 全局函数的声明, extern可加可不加, 但最好加上以表名是全局函数
- int main(void)
- {
- globalMethod();
- cout << "g_int:" << g_int << '\n';
- return 0;
- }
对于库的话, 全局函数一般会以.h头文件的形式开放出来, 不然谁知道库中有哪些函数呢!
上面的就会提取出一个Global.h:
Global.h
- #ifndef GLOBAL_H_
- #define GLOBAL_H_
- extern int g_int;
- extern void globalMehtod();
- #endif
然后在Main.cpp中:
Main.cpp
- #include <iostream>
- #include "Global.h"
- using namespace std;
- int main(void)
- {
- globalMethod();
- cout << "g_int:" << g_int << '\n';
- return 0;
- }