【无标题】

C++ static 修饰全局变量时的作用探究

作为一个c++开发者,我们面试时经常被问到 static 变量的作用,其中有一个问题是,static 修饰全局变量时起什么作用

通常我们会回答,"static 修饰全局变量时代表限制这个变量为此源文件可见,其他源文件无法访问到这个变量"。

但是之前我更多的是认为重点在于限制作用域,今天的一个小实验让我对它有了更深入的体会。

这里先问一个问题。

如果我们 在 某个头文件中声明一个 static 变量,然后用两个 source file 来引用它,可以做到共享全局变量通信吗?换句话说,某个 cpp 文件改动了它的值,另一个cpp能感知到吗?

答案是不会,实验表明,每一个源文件单独有一份属于自己的static 变量,所以一个源文件的更改不会影响到另一个源文件,这正是面试八股文里 "限制变量为本源文件可见的真正含义"。

  • 头文件 schema.h
cpp 复制代码
#ifndef __SCHEMA__
#define __SCHEMA__
#include <string>

static std::string input_schema = R"(this is input schema)";

#endif
  • 源文件 A help.cpp
cpp 复制代码
#include "help.hpp"

#include <iostream>
using namespace std;
void change_input() {
  input_schema = "new input schema";
  return;
}

void show_input() {
  cout << "help.cpp: " << input_schema << endl;
  cout << "help.cpp: " << &input_schema << endl;
  return;
}
  • 源文件 B main.cpp
cpp 复制代码
#include <iostream>

#include "help.hpp"
// #include "schema.h"
using namespace std;

int main() {
  cout << "main.cpp: " << input_schema << endl;
  change_input();
  cout << "main.cpp: " << input_schema << endl;
  show_input();
  // 打印地址
  cout << "main.cpp: " << &input_schema << endl;
  return 0;
}

输出

main.cpp: this is input schema

main.cpp: this is input schema

help.cpp: new input schema

help.cpp: 0x5631f26841a0

main.cpp: 0x5631f2684180

可以看出, 源文件A(help.cpp) 对 input_schema 的修改只有它自身感知到了,没有影响到 源文件B.

从打印的地址也可以看出,这是两个变量。

相关推荐
Lhan.zzZ2 小时前
笔记_2026.4.28_004
c++·ide·笔记·qt
wuminyu3 小时前
专家视角看Java字节码加载与存储指令机制
java·linux·c语言·jvm·c++
木喃的井盖4 小时前
无锁队列细节
c++·工程
王老师青少年编程4 小时前
csp信奥赛C++高频考点专项训练之字符串 --【字符串基础】:输出亲朋字符串
c++·字符串·csp·高频考点·信奥赛·专项训练·输出亲朋字符串
WBluuue5 小时前
数据结构与算法:莫队(一):普通莫队与带修莫队
c++·算法
KuaCpp5 小时前
C++面向对象(速过复习版)
开发语言·c++
智者知已应修善业8 小时前
【51单片机不用数组动态数码管显示字符和LED流水灯】2023-10-3
c++·经验分享·笔记·算法·51单片机
AI进化营-智能译站9 小时前
ROS2 C++开发系列16-智能指针管理传感器句柄|告别ROS2节点内存泄漏与野指针
java·c++·算法·ai
报错小能手9 小时前
好好讲讲移动构造 移动赋值
c++
syker9 小时前
AIFerric深度学习框架:自研全栈AI基础设施的技术全景
开发语言·c++