You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSAPP符号解析规则2与GCC编译多定义错误的疑问

链接阶段符号解析疑问:强/弱符号规则与实际编译冲突

正在学习链接阶段的符号解析,《CSAPP》中的规则2指出:当存在一个强符号和多个弱符号时,链接器会选择强符号。但以下实验却出现了多定义错误,似乎不符合该规则。

实验代码

strong.c

int x = 20;

weak.c

#include <stdio.h>

int x;

int main() {
    printf("%c\n", x);
    return 0;
}

编译环境及操作步骤

编译环境版本:

$ gcc --version
gcc (Ubuntu 12.2.0-3ubuntu1) 12.2.0
Copyright (C) 2022 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

编译及链接操作:

$ gcc -c strong.c
$ gcc -c weak.c

$ gcc weak.o strong.o
/usr/bin/ld: strong.o:(.data+0x0): multiple definition of `x'; weak.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status

符号查看结果

使用nm命令查看目标文件中的符号:

$ nm strong.o
0000000000000000 D x
$ nm weak.o
0000000000000000 T main
                 U printf
0000000000000000 B x

其中weak.o中的x是B标记(未初始化全局变量,弱符号),strong.o中的x是D标记(初始化全局变量,强符号)。

内容的提问来源于stack exchange,提问作者Guanwei HU

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 11:20:28