本文内容无意间搜到,正好之前也有这个困惑,所以转来做个备份:
引入问题;
我写了一个简单的汇编语言例程,text.s
section .text .globl _start _start: movq $1, %rax movq $0, %rbx int $0x80
用下面的ld脚本test.lds进行链接
SECTIONS { . = 0x10; label_1 = .; custom_section : { . = 0x20; label_2 = . ; label_3 = ABSOLUTE(.) ; *(.text) ; } }
链接命令为:
as test.c -o test.o && ld test.o -o test -T test.lds
然后查看符号地址:
nm test
结果如下:
0000000000000010 T label_1 0000000000000030 T label_2 0000000000000030 A label_3 0000000000000030 T _start
于是这产生了一个疑问,label_2为什么是0x30?
按照 ld 手册的描述:
. actually refers to the byte offset from the start of the current containing object. Normally this is the SECTIONS statement, whose start address is 0, hence . can be used as an absolute address. If . is used inside a section description however, it refers to the byte offset from the start of that section, not an absolute address.
这说得很明白,. 在custom_section内部表示一个偏移量而不是绝对地址,内部的点和外部的点不是一个东西,应该是互相隔离的。那把0x20赋值给.,再把.赋值给label_2 ,理论上说label_2 就应该等于0x20才对,但是为何链接后是0x30 呢,这不就成了绝对地址了吗?
别人的回答:
翻 ld 文档的 3.10.8.
3.10.8 The Section of an Expression
In the following simple example,
===============================================================
翻了半天文档,上边的例子就正好说明了这个问题吧。
转自:https://www.zhihu.com/question/271175871/answer/362725447