【发布时间】:2012-03-09 14:49:49
【问题描述】:
我正在尝试在 ASM 中创建一个共享库 (*.so),但我不确定我是否正确...
我的代码是:
.section .data
.globl var1
var1:
.quad 0x012345
.section .text
.globl func1
func1:
xor %rax, %rax
# mov var1, %rcx # this is commented
ret
要编译它,我运行
gcc ker.s -g -fPIC -m64 -o ker.o
gcc ker.o -shared -fPIC -m64 -o libker.so
我可以从 C 程序中访问变量 var1 并使用 dlopen() 和 dlsym() 调用 func1。
问题出在变量 var1 中。当我尝试从 func1 访问它时,即取消注释该行时,编译器会生成错误:
/usr/bin/ld: ker.o: relocation R_X86_64_32S against `var1' can not be used when making a shared object; recompile with -fPIC
ker.o: could not read symbols: Bad value
collect2: ld returned 1 exit status
我不明白。我已经用-fPIC编译过了,怎么回事?
【问题讨论】:
-
添加一个全局函数,改为返回var1的地址。
-
@HansPassant:实际上已经有一个指针变量保存了 var1 的地址,它被称为
var1@GOTCREL,并且可以通过 rip 相对位置无关代码访问。
标签: gcc assembly linker shared-libraries x86-64