gpt4 book ai didi

c++ - C++ 编译器如何找到外部变量?

转载 作者:行者123 更新时间:2023-12-02 07:29:01 24 4
gpt4 key购买 nike

我用g++和clang++编译这个程序。有一个区别:
g++ 打印 1,但 clang++ 打印 2。
看来
g++:外部变量定义在最短的范围内。
clang++:外部变量定义在最短的全局范围内。

C++ 规范对此有任何规范吗?

main.cpp

#include <iostream>
static int i;
static int *p = &i;

int main() {
int i;
{
extern int i;
i = 1;
*p = 2;
std::cout << i << std::endl;
}
}

其他.cpp

int i;

版本:g++:7.4.0/clang++:10.0.0
编译:$(CXX) main.cpp other.cpp -o extern.exe

最佳答案

[basic.link/7]应是标准的相关部分。在当前的草案中,它说:

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.

请注意,后续示例几乎与您的情况完全匹配:

static void f();
extern "C" void h();
static int i = 0; // #1
void g() {
extern void f(); // internal linkage
extern void h(); // C language linkage
int i; // #2: i has no linkage
{
extern void f(); // internal linkage
extern int i; // #3: external linkage, ill-formed
}
}

因此,该程序应该是格式错误的。解释如下示例:

Without the declaration at line #2, the declaration at line #3 would link with the declaration at line #1. Because the declaration with internal linkage is hidden, however, #3 is given external linkage, making the program ill-formed.

关于c++ - C++ 编译器如何找到外部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59624375/

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