如果在在多个.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*