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