gpt4 book ai didi

c - 链接器没有显示任何错误,很奇怪

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

假设我有 2 个 C src 文件,A1.C,A2.C,这些是内容:

A1.C

int x;
int main(){
void f(void);

x = 5;
f();
printf("%d", x);

return 0;
}

A2.C

int x;
void f() { x = 4; }

尽管缺少“extern”安全词,链接器没有给我任何错误。我有 2 个相同的符号。有人可以解释为什么吗?

最佳答案

对于 gcc,您可以使用 -fno-common 标志将其转换为错误。

gcc 文档解释了发生了什么

-fno-common

In C code, controls the placement of uninitialized global variables. Unix C compilers have traditionally permitted multiple definitions of such variables in different compilation units by placing the variables in a common block. This is the behavior specified by -fcommon, and is the default for GCC on most targets.

On the other hand, this behavior is not required by ISO C, and on some targets may carry a speed or code size penalty on variable references.

The -fno-common option specifies that the compiler should place uninitialized global variables in the data section of the object file, rather than generating them as common blocks. This has the effect that if the same variable is declared (without extern) in two different compilations, you get a multiple-definition error when you link them.

另见 Tentative definitions in C99 and linking

关于c - 链接器没有显示任何错误,很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24471594/

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