方法:
在xxx.h中利用extern关键字声明全局变量
extern int a;
在xxx.cpp中#include<xxx.h>
再定义 int a;
赋不赋初值无所谓,之后该全局变量a就可以被任何包含xxx.h的文件所访问了
例子:
main.cpp:
#include <iostream>
#include <header1.h>
#include <header2.h>
using namespace std; int main()
{
a=1;
b=2;
cout<<a;
pB();
pa();
return 0;
}
header1.cpp:
#include <header1.h>
int a;
int b;
void pB()
{
cout<<b;
}
header1.h:
#ifndef HEADER1_H_INCLUDED
#define HEADER1_H_INCLUDED
#include <iostream>
using namespace std;
extern int a;
extern int b;
void pB();
#endif // HEADER1_H_INCLUDED
header2.h:
#ifndef HEADER2_H_INCLUDED
#define HEADER2_H_INCLUDED
#include <header1.h>
void pa()
{
a=6;
cout<<a;
}
#endif // HEADER2_H_INCLUDED