编辑: 我通过使用
ld -o output main.o -L /lib/gcc/x86_64-linux-gnu /lib/x86_64-linux-gnu/crti.o /lib/x86_64-linux-gnu/crtn.o /lib/x86_64-linux-gnu/crt1.o -dynamic-linker /lib64/ld-linux-x86-64.so.2 -lc
而不是 ld -o output main.o -e main
来实现它。看来这些文件是链接成功运行可执行文件所必需的。
我有这个简单的 LLVM IR 代码,只是返回退出代码“15”,顺便说一句。我使用 LLVM 17:
; ModuleID = 'main.ll'
source_filename = "main"
; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(none)
define i32 @main() local_unnamed_addr #0 {
main:
ret i32 15
}
attributes #0 = { mustprogress nofree norecurse nosync nounwind willreturn memory(none) }
我使用以下命令将 LLVM IR 转换为 .o 文件:
llc-17 -filetype=obj main.ll -o main.o
最后使用(我也尝试过 ld.lld)链接 main.o 文件:
ld -o output main.o -e main
如果我运行输出 (./output),则会收到分段错误错误。
这可能有帮助:
的输出:objdump -D main.o
main.o: file format elf64-x86-64
Disassembly of section .text:
0000000000000000 <main>:
0: b8 0f 00 00 00 mov $0xf,%eax
5: c3 ret
的输出:file output
output: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped
我也尝试使用gdb进行调试,如下:gdb ./output, (gdb) run, output:
Starting program: /.../output
Program received signal SIGSEGV, Segmentation fault.
0x0000000000000001 in ?? ()
然后
bt
(回溯):
#0 0x0000000000000001 in ?? ()
#1 0x00007fffffffdce6 in ?? ()
#2 0x0000000000000000 in ?? ()
还有
info registers
:
rax 0xf 15
rbx 0x0 0
rcx 0x0 0
rdx 0x0 0
rsi 0x0 0
rdi 0x0 0
rbp 0x0 0x0
rsp 0x7fffffffd8d8 0x7fffffffd8d8
r8 0x0 0
r9 0x0 0
r10 0x0 0
r11 0x0 0
r12 0x0 0
r13 0x0 0
r14 0x0 0
r15 0x0 0
--Type <RET> for more, q to quit, c to continue without paging--c
rip 0x1 0x1
eflags 0x10202 [ IF RF ]
cs 0x33 51
ss 0x2b 43
ds 0x0 0
es 0x0 0
fs 0x0 0
gs 0x0 0
k0 0x0 0
k1 0x0 0
k2 0x0 0
k3 0x0 0
k4 0x0 0
k5 0x0 0
k6 0x0 0
k7 0x0 0
我通过使用 ld -o output main.o -L /lib/gcc/x86_64-linux-gnu /lib/x86_64-linux-gnu/crti.o /lib/x86_64-linux-gnu/crtn.o 让它工作/lib/x86_64-linux-gnu/crt1.o -dynamic-linker /lib64/ld-linux-x86-64.so.2 -lc 而不是 ld -o 输出 main.o -e main.看来这些文件是链接成功运行可执行文件所必需的。