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
运行得到结果如下图所示:
可以看到,各个cpp里面的函数都能对全局变量进行修改,得到的全局变量的值都是最新的。
阅读全文
0 0
- C++跨文件共享全局变量
- 关于全局变量,如何被多个.c文件共享问题
- 关于全局变量,如何被多个.c文件共享问题
- 关于全局变量,如何被多个.c文件共享问题
- C++多文件共享全局变量
- C语言中跨文件的全局变量
- C/C++多文件共享全局变量时,使用extern的规范
- C/C++多文件共享全局变量时,使用extern的规范
- C语言中全局变量的共享
- C语言中全局变量的共享
- 多文件共享全局变量和函数
- const 全局变量 全局变量 跨文件访问。
- python中如何在不同文件间共享全局变量
- python中如何在不同文件间共享全局变量
- python在不同文件之间共享全局变量方案的探讨
- C++多文件间函数调用及全局变量共享问题
- C语言全局变量多文件使用
- C语言全局变量多文件使用
- 2017 GCTF Web WriteUp
- 三数之和
- java语言基础(67)——集合框架之数据结构
- 短地址(ShortUrl)实例
- JS学习笔记(二)
- C++跨文件共享全局变量
- 操作系统
- pyenv & pyenv-virtualenv
- 欢迎使用CSDN-markdown编辑器
- mac 安装 golang 1.8
- docker学习
- ReetrantLock源码解析(一):获得公平锁和非公平锁lock()
- Apple Mach-O Linker Error 一个粗心造成的问题
- 《Effective Java》 第二讲:对于所有对象都通用的方法