C++跨文件共享全局变量

来源:互联网 发布:淘宝达人直播的入口 编辑:程序博客网 时间:2024/05/16 14:48

1.问题描述

最近做项目的时候需要在多个cpp文件之间通过全局变量传递参数,因此写了一个小程序来尝试一下。

2.解决方法

一共用到5个文件:test1.h, test1.cpp test2.h test2.cpp main.cpp

test1.h

#ifndef TEST1_H#define TEST1_H#include <iostream>#include <string>#include <vector>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

运行得到结果如下图所示:
cross_file

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