C++ 中实现多文件共享变量的方式
以下内容为个人临时笔记,不保证绝对正确
- 定义全局变量 并在引用该变量的文件中使用extern 声明
例如:
main.cpp 中
int a = 0;
std::cout << "a:" << a << std::endl;
test.cpp 中
extern int a;
std::cout << "a:" << a << std::endl;
- 定义一个单独的头文件,在里面进行变量声明,再在使用其的文件中添加引用
定义var.hpp
var.hpp
#ifndef _VAR_H_
#define _VAR_H_
static int a; // 定义变量
#endif
main.cpp
#include "var.hpp"
std::cout << "a:" << a << std::endl;
test.cpp
#include "var.hpp"
std::cout << "a:" << a << std::endl;