链接程序如何解析C中的乘法定义的全局符号 [英] How Linkers Resolve Multiply Defined Global Symbols in C

查看:128
本文介绍了链接程序如何解析C中的乘法定义的全局符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的教科书说:

函数和已初始化的全局变量获得强符号.未初始化的全局变量获得弱符号.给定一个强符号和多个弱符号,选择强符号"

所以我创建了两个文件来查看:

So I create two files to see:

file1.c:

int number;

int main(int argc, char *argv[]) 
{
    printf("%d",number);
    return 0;
}

file2.c(仅一行):

file2.c (just one line):

int number = 2018;

,然后运行gcc -Wall -o program file1.c file2.c,输出为0,在研究链接器之前(文件1.c中的'number'已被初始化为0),我可以理解,但是在研究链接器的工作原理之后,我开始怀疑为什么输出的不是2018年,因为file2中的'number'是强符号(已初始化的全局变量),而file1中的'number'是弱符号,所以链接器将选择值为2018的强数字,所以为什么链接器选择弱符号?

and I ran gcc -Wall -o program file1.c file2.c and the output is 0, which I can understand before I study linker ('number' in file1.c has been initialized to 0), but after I study how linker works, I start to wonder why the output is not 2018, since the 'number' in file2 is strong symbol(initialized global variable) and the 'number' in file1 is weak symbol, so the linker will choose the strong one whose value is 2018, so why the linker choose the weak symbol?

推荐答案

file1.c中的int number;尚未初始化.请注意,它是在文件范围内声明的,没有初始化程序就声明,并且没有存储类说明符(尤其是没有externstatic)声明.然后C 2018 6.9.2 2说:

The int number; in file1.c is not uninitialized. Note that it is declared at file scope, it is declared without an initializer, and it is declared without a storage-class specifier (particularly no extern or static). Then C 2018 6.9.2 2 says:

具有文件范围的对象(没有初始化程序),没有存储类说明符或具有存储类说明符static的对象的标识符声明构成临时定义.如果翻译单元包含一个或多个标识符的临时定义,并且翻译单元不包含该标识符的外部定义,则该行为就好像该翻译单元包含该标识符的文件范围声明,且复合类型为转换单元末尾的值,初始值设定为0.

A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storage-class specifier static, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definition for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.

因此,file1.c中的int number;int number = 0;相同.它已初始化.

So, int number; in file1.c is the same as int number = 0;. It is initialized.

您引用的文本有一个问题,就是它使用该链接器的术语来描述该链接器,这与C标准所使用的术语不同. C标准没有任何全局"变量或强"或弱"符号.

An issue with the text you quote is that it is describing the linker using terminology for that linker, and this is different terminology than the the C standard uses. The C standard does not have any "global" variables or "strong" or "weak" symbols.

这篇关于链接程序如何解析C中的乘法定义的全局符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆