C++使用全局变量

如果在在多个.cpp文件中都要用到某个变量,那么这个变量就是全局变量。

首先,在.h文件中声明这个变量,加上extern关键字,但是不能给变量赋值。比如在头文件a.h中这样写:

#ifndef _A_H
#define _A_H
extern int global;
#endif
在main()函数所在的文件种定义这个全局变量,可以初始化。

#include <iostream>

using namespace std;

void f1();
void f2();
int global;

int main()
{
    global = 1234;
    f1();
    f2();
    cout<<"main:global="<<global<<endl;
    return 0;
}
在main()函数中还声明了两个函数f1()和f2(),它们分别在a1.cpp和a2.cpp这两个文件中定义。在这两个文件中都用到了global这个全局变量,所以在这两个文件中要include头文件a.h

/*a1.cpp*/

#include <iostream>
#include "a.h"
using namespace std;

void f1()
{
    global = 1111;
    cout<<"f1:global="<<global<<endl;
}
/*a2.cpp*/

#include <iostream>
#include "a.h"
using namespace std;

void f2()
{
    global = 2222;
    cout<<"f2:global="<<global<<endl;
}
最后,同时编译a.cpp,a1.cpp,a2.cpp这3个文件
g++ -W a.cpp a1.cpp a2.cpp -o a
运行
./a
结果如下:
f1:global=1111
f2:global=2222
main:global=2222
posted @ 2012-05-23 19:10  simmerlee  阅读(373)  评论(0)    收藏  举报