gpt4 book ai didi

c++ - 有 extern 和没有 extern 的函数的局部/ block 作用域声明之间的区别

转载 作者:搜寻专家 更新时间:2023-10-31 01:34:48 27 4
gpt4 key购买 nike

在 C++ 中,extern(后面不跟语言链接字符串文字)似乎对命名空间范围 (Difference between declaration of function with extern and without it) 的函数声明没有影响。但它对 block 作用域函数声明有任何影响吗?或者没有 extern 的局部函数声明是否总是等同于带有 extern 的局部函数声明?

namespace {
void f() {
extern void g(); // has external linkage
g();
}
void f2() {
void g(); // always the same, as if, without extern
g();
}
}

谢谢!

最佳答案

这里的规则来自[basic.link]:

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 there is a visible declaration of an entity with linkage having the same name and type, ignoring entities declared outside the innermost enclosing namespace scope, 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.

所以 block 作用域函数声明有和没有 external 没有区别。但请注意有趣的例子:

static void f();

void g() {
extern void f(); // internal linkage
}

在这里, block 范围 f 重新声明 ::f 并接收相同的链接:内部。即使它被标记为 extern。但是 extern 关键字的存在与否并不重要

关于c++ - 有 extern 和没有 extern 的函数的局部/ block 作用域声明之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38588167/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com