@nrailgun
2015-09-14T17:05:09.000000Z
字数 754
阅读 2030
程序设计
-shared
选项导致 g++ 产生 shared library:
g++ -shared -o fus.so roh.o dah.o
当你尝试连接你会发现 g++ 报错:
g++ -shared -o fus.so roh.o dah.o
/usr/bin/ld: roh.o: relocation R_X86_64_32 against `.bss' can not be used when making a shared object; recompile with -fPIC
roh.o: error adding symbols: Bad value
collect2: error: ld returned 1 exit status
通过检查 LINUX g++ 手册,得到:
-fPIC
If supported for the target machine, emit position-independent code, suitable for dynamic linking and avoiding any limit on the size of the global offset table. This option makes a difference on the m68k, PowerPC and SPARC.
Position-independent code requires special support, and therefore works only on certain machines. When this flag is set, the macros "
__pic__
" and "__PIC__
" are defined to 2.
在编译器生成的代码中,符号的位置都是固定的(固定的虚拟地址)。但当你链接到动态库时候,符号的位置却是无法确定的。因此,编译动态库在编译时刻不决定地址,在运行时刻再做确定。