1.问题描述
最近做项目的时候需要在多个cpp文件之间通过全局变量传递参数,因此写了一个小程序来尝试一下。
2.解决方法
一共用到5个文件:test1.h, test1.cpp test2.h test2.cpp main.cpp
test1.h
#ifndef test1_h #define test1_h #include #include #include extern int global_v; void modify_1(); void print_1(); #endif
test1.cpp
#include "test1.h"
using namespace std;
int global_v = 1;
void modify_1()
{
global_v++;
cout << "in test1, value increases to " << global_v << endl;
}
void print_1()
{
cout << "in test1, value is " << global_v << endl;
}
test2.h
#ifndef test2_h #define test2_h #include "test1.h" void modify_2(); void print_2(); #endif
test2.cpp
#include "test2.h"
using namespace std;
void modify_2()
{
global_v++;
cout << "in test2,value increases to " << global_v << endl;
}
void print_2()
{
cout << "in test2, value is " << global_v << endl;
}
main.cpp
#include "test1.h"
#include "test2.h"
using namespace std;
int main()
{
cout << "in main function, initial global value is " << global_v << endl;
modify_1();
modify_2();
print_1();
print_2();
return 0;
}
编译
g++ -o main test1.cpp test2.cpp main.cpp
运行得到结果如下图所示:

可以看到,各个cpp里面的函数都能对全局变量进行修改,得到的全局变量的值都是最新的。
loveJx宝宝