当文件位于不同目录时,GNU 链接器 (ld) 会失败吗?

Does GNU linker (ld) fail when files are in different directories?

当我运行以下命令时,

ld -m elf_i386 -T kernel.ld -o img/kernel bin/entry.o bin/bio.o bin/console.o ... bin/main.o ... bin/proc.o ... bin/vm.o -b binary img/initcode img/entryother

我收到以下错误:

bin/main.o: In function `startothers':
main.c:75: undefined reference to `_binary_entryother_size'
main.c:75: undefined reference to `_binary_entryother_start'
bin/proc.o: In function `userinit':
proc.c:131: undefined reference to `_binary_initcode_size'
proc.c:131: undefined reference to `_binary_initcode_start'

但是,如果 kernel.ld,并且所有二进制文件都在同一目录中,link 完成且没有错误:

ld -m elf_i386 -T kernel.ld -o kernel entry.o bio.o console.o ... main.o ... proc.o ... vm.o -b binary initcode entryother

问题是 GNU link 还是转移注意力?

当创建 *_start*_end_size 符号时,对应于二进制数据,链接器从其命令行参数 中生成前缀是.

即链接器使用:

  • 参数 initcode
  • 的前缀 _binary_initcode_
  • 参数 img/initcode 的前缀 _binary_img_initcode_

据我所知,在调用链接器时不可能重新定义这个前缀。


使用 objcopy 可以创建一个包含 特定部分 的目标文件,其中包含来自其他文件的二进制数据:

objcopy -I binary -O <output-format> -B <architecture> --rename-section .data=.initcode,alloc,load,readonly,data,contents img/initcode <output-obj-file>

生成的目标文件可用于链接。在链接器的命令行中,需要使用自定义链接器 srcipt,它指定二进制部分的位置并创建表示其开始和结束的符号:

...
SECTIONS
{
   ...
   <output-section-name>:
   {
       ...
       initcode_start = .;
       *(.initcode);
       initcode_end = .;
       ...
   }
}