c++中全局变量与头文件

来源:互联网 发布:淘宝大学ps教程 编辑:程序博客网 时间:2024/05/18 20:48
最近碰到一个问题,想要在主文件中定义全局变量,其它文件也能够使用。通过查资料,找到了两种方法:一是在主文件的cpp中定义变量,在头文件.h中通过extern声明一下,要使用全局变量的其它cpp文件只要包含这个头文件就ok了;二是通过条件编译。

其中一是比较常用的方法,但是有一点一定要注意,就是头文件中只是声明,定义是在cpp文件中,千万不要弄反了!

下面之间看实现。。。。。。
方法一:
main.cpp:
#include <iostream>
#include "head.h"

using namespace std;

int a = 10;
int b = 20;

int main()
{
cout<<"this is main"<<a+b<<endl;
getData();
cout<<"this is main"<<a+b<<endl;
return 1;
}
sub.cpp:
#include <iostream>
#include "head.h"

using namespace std;

void getData()
{
a = 20;
cout<<"this is sub"<<a+b<<endl;
}
head.h:
extern int a;
extern int b;

void getData();


方法二:
main.cpp:
#include <iostream>
#define MAIN
#include "head.h"

using namespace std;

int main()
{
cout<<"this is main"<<a+b<<endl;
getData();
cout<<"this is main"<<a+b<<endl;
return 1;
}
sub.cpp:
同上
head.h:
#ifdef MAIN
int a = 10;
int b = 20;
#else
extern int a;
extern int b;
#endif

void getData();


转自:http://blog.163.com/tfn2008@yeah/blog/static/11032131920126105132537/

0 0