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

标签 c linker static-linking extern linkage

假设我有 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/

相关文章:

c - 贝尔曼福特图算法

c - 如何从汇编调用 C 函数

c - 用两个指针搜索链表

c++ - 在 QT 中链接 libCurl 给出了一个巨大的错误列表 C++

linux - 如何准确查看链接到我的程序中的内容?

c++ linux双重销毁静态变量。链接符号重叠

c++ - 如何在 Qt Creator 中静态构建非 Qt 项目

c - 在 C 中查找子字符串

奇怪的只读符号显示在初始化数据部分(D)中,单位为 nm

c++ - 在 C++ Visual Studio 中链接静态库