gpt4 book ai didi

c++ - 根据 C++17 标准草案在 block 作用域中声明为 `extern` 的函数的链接

转载 作者:太空狗 更新时间:2023-10-29 23:13:03 25 4
gpt4 key购买 nike

来自C++17 Standard Draft § 3.5.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 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

此外,标准中还提供了一个示例:

static void f();
static int i = 0; // #1
void g() {
extern void f(); // internal linkage
int i; // #2 i has no linkage
{
extern void f(); // internal linkage
extern int i; // #3 external linkage
}
}

第三个函数声明extern void f()是否接收:

  • external 链接(由于前面的 extern void f() 声明)
  • internal 链接(因为上面 block 作用域中 f() 的第二个声明从 f() 的声明接收内部链接在 :: 全局命名空间中)
  • 或者它是病态的因为有不止一个这样的匹配实体”?

编辑

main.cpp

#include <iostream>

extern void g();
void f() { std::cout << "main f() called" << std::endl; }

int main(){
g();
return 0;
}

测试.cpp:

#include <iostream>

static void f() { std::cout << " test f() called" << std::endl; }
void g() {
extern void f();
{
extern void f();
f();
}
}

g()main.cppmain() 函数中被调用。
使用 gcc 5.4.0

编译

g++ -std=c++14 -Wall main.cpp test.cpp

打印:

main f() called

因此,gcc 显然将 g() 中的 f() 调用与 external 链接(调用在main.cpp 文件)。标准示例中的注释是错误的(#3 的函数声明没有内部链接)或者它是来自 gcc 的编译器错误。

最佳答案

我不明白你的困惑。最里面的封闭命名空间范围是 global namespace 的范围;第一个和第二个声明在类型和名称上匹配,因此外部 block 范围声明仅继承全局声明的链接(由于 static 说明符,它是内部的)。第二个 block 作用域声明与第一个关联;你明白了。

关于c++ - 根据 C++17 标准草案在 block 作用域中声明为 `extern` 的函数的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41978949/

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