c++ - 用说明符extern声明的C++中的标识符链接

标签 c++ c++17 constants extern linkage

在C标准(6.2.2标识符的链接)中,写得足够清楚

4 For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible,31) if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.



但是,通过C++标准的6.5程序和链接一节,我找不到类似的声明。

出现此问题的原因是来自C++ 17 Standard的以下引用

3 A name having namespace scope (6.3.6) has internal linkage if it is the name of

(3.2) — a non-inline variable of non-volatile const-qualified type that is neither explicitly declared extern nor previously declared to have external linkage; or



现在考虑以下声明
const int x = 100;
extern const int x;

因此,虽然代码是用说明符x声明的,还是标准段落的描述有缺陷,或者我错过了C++标准中与引号类似的引号,但仍不清楚代码是否格式错误或常量extern是否具有内部链接。引用C标准。

最佳答案

可能是basic.link#6的缺陷,查看了dcl.stc#5之后,它说:

For the linkage of a name declared with an extern specifier, see [basic.link].


但是,有关使用extern说明符声明的声明的规则主要位于[basic.link#6]中,即:

The name of a function declared in block scope and the name of a variable declared by a block scope extern declaration have linkage. If such a declaration is attached to a named module, the program is ill-formed. If there is a visible declaration of an entity with linkage, ignoring entities declared outside the innermost enclosing namespace scope, such that the block scope declaration would be a (possibly ill-formed) redeclaration if the two declarations appeared in the same declarative region, the block scope declaration declares that same entity and receives the linkage of the previous declaration. If there is more than one such matching entity, the program is ill-formed. Otherwise, if no matching entity is found, the block scope entity receives external linkage. If, within a translation unit, the same entity is declared with both internal and external linkage, the program is ill-formed.


听起来这些规则仅适用于块范围声明,而不适用于使用extern说明符声明的 namespace 范围声明。除本段外,[basic.link]节中没有其他规则指示extern说明符声明的名称的链接。与C标准中所说的不同,这些规则适用于用extern说明符声明的任何声明(无论声明在哪种范围内声明)。

关于c++ - 用说明符extern声明的C++中的标识符链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60159969/

相关文章:

c++ - 使文件在Windows中可写

c++ - stringstream 是否应该将 "INFINITY"解析为无限值?

c++ - 如何让一个变量依赖于一个类中的其他变量?

c++ - 删除指向 const (T const*) 的指针

python - Boost.Python:如何公开 std::unique_ptr

C++ 运算符优先级和返回语句

c++ - 多次使用 [x, y, z, ...]-clause 语法,不应该允许 operator[] 接受多个参数吗?

c++ - 进程终止,状态为 -1073741571(0 分钟,3 秒)

c++ - 返回一个 const 引用和非 const 成员函数调用

无法使用我认为应该是编译时常量的内容来初始化静态数组