c++ - 为什么const int需要extern而不是const char *

标签 c++ c++17 extern

我对为什么在extern.cpp文件中的定义中是否需要externint而不需要char*感到困惑。我有以下测试程序:

// extern.cpp
extern const int my_int = 1;
const char* my_str = "FOO";
// main.cpp
#include <iostream>

extern const int my_int;
extern const char* my_str;

int main() {
  std::cout << my_int;
  std::cout << my_str;
  return 0;
}
如果我从extern中删除extern const int my_int = 1;,那么我会得到undefined reference to 'my_int'。如果将extern添加到const char* my_str = "FOO";,则会收到警告'my_str' initialized and declared 'extern'。为什么我需要在extern上添加my_int,但将其添加到my_str会生成警告?
这是gcc 10.1.0上的C++ 17。具体命令为:
/usr/bin/g++-10  -g -std=gnu++17 -o main.cpp.o -c main.cpp
/usr/bin/g++-10  -g -std=gnu++17 -o extern.cpp.o -c extern.cpp
/usr/bin/g++-10  -g main.cpp.o extern.cpp.o -o TestExtern

最佳答案

这是由my_intmy_str变量的不同linkage引起的。my_int是命名空间范围内的const限定变量,这意味着默认情况下它具有内部链接。换句话说,除非您将其标记为extern,否则它的可见性仅限于当前翻译单元。此外,内部链接常量必须具有一个初始化程序。
另一方面,my_str不是const限定的。请勿将const限定符与指针类型混淆,因为该限定符是指针类型的一部分。指针本身是可变的,您可以在运行时为其分配一个不同的值。由于这是 namespace 范围内的非const变量,因此它具有外部链接,因此在整个程序范围内引用单个指针对象。

关于c++ - 为什么const int需要extern而不是const char *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65813523/

相关文章:

c++ - extconf.rb:如何生成依赖于头文件更改的 makefile 目标?

android - 在 Android 中读取共享首选项期间,Qt 上的 JNI 出现 NoSuchMethodError

c - 如何使用 C99 实现和共享内联函数?

c++ - 按位重载 OR ('|' ) 链接操作未按预期工作

c++ - 为什么我的 C 程序可以从 C++ 文件调用函数而不包含 header ?

c++ - 查找全局变量而不是在 C++ 函数中构造它们

c++ - VS2015 提示 printf 没有内联

c++ - 将原始数据 "signature"写入磁盘而不损坏文件系统

c++ - 多态分配器 : when and why should I use it?

c++ - c++17 的 std::ptr_fun 替换