Shared library on Linux and -fPIC error
Asked Answered
R

1

7

I am trying to compile a shared library in Linux using a Makefile created with Cmake, but running make I obtain the following error:

   Linking CXX shared library libcpp-lib.so
   /usr/bin/ld: /home/davide/Desktop/boost_1_55_0/stage/lib/libboost_system.a(error_code.o): relocation R_X86_64_32 against .rodata.str1.1 can  not be used when making a shared object; recompile with -fPIC
   /home/davide/Desktop/boost_1_55_0/stage/lib/libboost_system.a: could not read symbols:   Bad value
   collect2: ld returned 1 exit status
   make[2]: *** [libcpp-lib.so] Error 1
   make[1]: *** [CMakeFiles/cpp-lib.dir/all] Error 2
   make: *** [all] Error 2

I provide the following command in the CMakeLists.txt in order to say that I want a shared (.so) library:

add_library(cpp-lib SHARED ${CPP_FILES})

What else do I need to specify in order to avoid the -fPIC error shown above?

Thanks a lot in advance

Ricarda answered 24/10, 2014 at 13:43 Comment(0)
I
9

The boost libraries needs to be compiled using -fPIC: Please have a look at: How to compile static library with -fPIC from boost.python

Try to add compiler flags by cmake by in your project:

set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
Institutor answered 24/10, 2014 at 13:46 Comment(2)
I have same problem. Done that. No result. At start I write: set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fPIC") set(CMAKE_C_FLAGS "$CMAKE_C_FLAGS -fPIC") After "add_library" I add: SET_TARGET_PROPERTIES(${PROJECT_NAME} PROPERTIES COMPILE_FLAGS "-fPIC") No result. At all. How else to solve that? Problem goes with libboost_system.a.Factual
setting CMAKE_POSITION_INDEPENDENT_CODE or usage of POSITION_INDEPENDENT_CODE target property is better way as it is compiler independent. Also CMAKE_*_FLAGS manipulation is not so good as user may change it in cache fileLagomorph

© 2022 - 2024 — McMap. All rights reserved.