目录
效果
项目
代码
下载
为了实现跨文件共享全局变量,我们可以使用 extern 关键字。extern 关键字用于声明一个变量,该变量在其他地方已经定义。它告诉编译器这个变量在其他文件中已经定义了,不需要重新分配内存空间,只需要引用即可。
效果
项目
代码
Common.h
#pragma once#include <iostream>using namespace std;struct para {bool state;int num;string name;
};//声明全局变量
extern para g_static_para;
Common.cpp
#pragma once
#include "Common.h"//定义全局变量
para g_static_para;
init_class.h
#pragma once#include <iostream>
#include "Common.h"using namespace std;class init_class
{public:void init();};
init_class.cpp
#include "init_class.h"
#include "Common.h"void init_class::init()
{cout << "参数初始化 全局变量 g_static_para" << endl;g_static_para.state = true;g_static_para.num = 20;g_static_para.name = "测试信息2";
}
use_class.h
#pragma once#include <iostream>
#include "Common.h"using namespace std;class use_class
{public:void print();};
use_class.cpp
#include "use_class.h"void use_class::print() {cout << "打印参数 全局变量 g_static_para" << endl;cout << "g_static_para.state:" << g_static_para.state << endl;cout << "g_static_para.num:" << g_static_para.num << endl;cout << "g_static_para.name:" << g_static_para.name << endl;
}
ConsoleApplication1-test.cpp
#pragma once
#include <iostream>
#include "Common.h"
#include "init_class.h"
#include "use_class.h"using namespace std;int main()
{std::cout << "Hello World!\n";init_class ic;use_class uc;std::cout << "----------------------\n";g_static_para.state = false;g_static_para.num = 10;g_static_para.name = "测试信息1";uc.print();std::cout << "----------------------\n";ic.init();std::cout << "----------------------\n";uc.print();
}
下载
Demo下载