C++ const 全局变量跨文件引用,无法解析的外部符号?

问题描述

前两天群里有人问了这样一个问题:

在 a 文件中定义了一个全局变量,可以在 b 文件中引用。但一旦把全局变量改为 const 之后,就无法在 b 文件中引用,编译(链接)报错“无法解析的外部符号”,这是为什么?

解析

这是因为 const 修饰的全局变量默认具有文件作用域(类比C语言中的static变量),如果想和非 const 变量一样具有全局作用域,需要在定义时(不仅仅只是声明时)显式地增加 extern 关键字。

Talk is cheap, show me the code!

1. 普通全局变量

// a.cpp
int g = 3;
// b.cpp
#include<iostream>
extern int g;
int main() {
  std::cout << g << std::endl;
}

g++ a.cpp b.cpp && ./a.out 成功编译、运行

2. const 全局变量

// a.cpp
const int g = 3;
// b.cpp
#include<iostream>
extern const int g; // 链接报错,无法解析的外部符号,找不到 g 的定义!
int main() {
  std::cout << g << std::endl;
}

因为 a 中的 const 变量默认具有文件作用域,在 a.cpp 之外不可见。因此在链接阶段报错,无法解析的外部符号,找不到 g 的定义!

3 定义 const 变量时增加 extern

// a.cpp
extern const int g = 3; // 增加 extern
// b.cpp
#include<iostream>
extern const int g;
int main() {
  std::cout << g << std::endl;
}

强制 const 变量具有全局作用域,成功编译、运行!

posted @ 2024-01-21 16:51  Zijian/TENG  阅读(135)  评论(0编辑  收藏  举报