gpt4 book ai didi

c - 通过 `extern` 变量访问 .text 段是否会导致未定义的行为?

转载 作者:太空宇宙 更新时间:2023-11-04 02:57:26 24 4
gpt4 key购买 nike

这是文件“1.c”

    #include <stdio.h>
char foo;
int bar(){
}
int main(){
printf("%d",foo);
return 0;
}
//--------------------------

这是文件“2.c”

    void foo(){
}

编译器调用为 gcc 1.c 2.c

以上是否给出了未定义的行为?我的猜测是,是的。否则几乎不可能进行优化。

Multiple different definitions for the same entity (class, template, enumeration, inline function, static member function, etc.) [What are all the common undefined behaviour that a C++ programmer should know about?

但据我所知,char foo 仅生成一个弱符号,它可以在链接时被 void foo(){} 覆盖.此外,如果我将 char foo 更改为 extern char foo,这仍然是一个定义吗?

最佳答案

它会导致未定义的行为,是的。标准中可能有很多引述对各种类型的声明等是明确的,但总结如下:

In the set of translation units and libraries that constitutes an entire program, eachdeclaration of a particular identifier with external linkage denotes the same object orfunction. (6.2.2)

All declarations that refer to the same object or function shall have compatible type;otherwise, the behavior is undefined. (6.2.7)

char foo; 在您的示例中是一个暂定定义。如果你使用 extern,它就不是一个定义,但它仍然是一个声明,上面的内容仍然适用。

关于c - 通过 `extern` 变量访问 .text 段是否会导致未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15890980/

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