"重定位R_X86_64_32S反对"链接错误

Thi*_*jan 54 c++ linux shared-libraries static-libraries

我正在尝试将静态库链接到共享库,我收到了以下错误

/usr/bin/ld: ../../../libraries/log4cplus/liblog4cplus.a(fileappender.o): relocation R_X86_64_32S against `a local symbol' can not be used when making a shared object; recompile with -fPIC
../../../libraries/log4cplus/liblog4cplus.a: could not read symbols: Bad value
collect2: ld returned 1 exit status

但这适用于32位机器而没有任何此类错误.我尝试-fPIC手动将标志添加到Makefile,但也没有解决问题

-whole-archive按照这里的建议尝试了旗帜,但没有成功.

 
/usr/bin/ld: ../../../libraries/log4cplus/liblog4cplus.a(appenderattachableimpl.o): relocation R_X86_64_32S against `vtable for log4cplus::spi::AppenderAttachable' can not be used when making a shared object; recompile with -fPIC
../../../libraries/log4cplus/liblog4cplus.a(appenderattachableimpl.o): could not read symbols: Bad value
collect2: ld returned 1 exit status

创建liblog4cplus.a:

  1. unzip log4cplus-1.1.0.zip
  2. ./configure --enable-static=yes --enable-threads=yes
  3. vi Makefile 并将-fPIC添加到CXXFLAGS和CFLAGS
  4. make

然后编译我的共享库:

  1. g++ -frtti -w -c -fPIC -I"Include_Directory" myfile.cpp
  2. g++ -shared -fPIC -frtti -I"Include_Directory" -o mysofile.so myfile.o -Wl,--whole-archive "../../../libraries/log4cplus/liblog4cplus.a" -Wl,--no-whole-archive -ldl

fon*_*ons 86

假设您正在生成一个共享库,很可能发生的是liblog4cplus.a您正在使用的变体未编译-fPIC.在linux中,您可以通过从静态库中提取目标文件并检查它们的重定位来确认:

ar -x liblog4cplus.a  
readelf --relocs fileappender.o | egrep '(GOT|PLT|JU?MP_SLOT)'
Run Code Online (Sandbox Code Playgroud)

如果输出为空,则静态库不是与位置无关的,不能用于生成共享对象.

由于静态库包含已编译的目标代码,因此提供-fPIC标志将无济于事.

您需要获得liblog4cplus.a编译版本-fPIC并使用该版本.


小智 11

添加在和-fPIC的末尾CMAKE_CXX_FLAGSCMAKE_C_FLAG

例子:

set( CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} -Wall --std=c++11 -O3 -fPIC" )
set( CMAKE_C_FLAGS  "${CMAKE_C_FLAGS} -Wall -O3 -fPIC" )
Run Code Online (Sandbox Code Playgroud)

这解决了我的问题。