Steve Lorimer
Steve Lorimer

Reputation: 28659

How to link against PIC version of a library's dependency in CMake?

CMake:

We have a dependency on cpp-netlib.

We build it from source as part of our build system.

cpp-netlib/CMakeLists.txt:

add_library(cpp-netlib
    STATIC
    ${SRCS})

For one particular use case, we have to use it in a shared library, so I've created a second library with -fPIC enabled:

add_library(cpp-netlib_pic
    STATIC
    ${SRCS})
set_property(TARGET cpp-netlib_pic PROPERTY POSITION_INDEPENDENT_CODE)

In my shared library target, I then link against libcpp-netlib_pic.a

foo/CMakeLists.txt:

add_library(foo
    SHARED
    ${SRCS})
target_link_libraries(foo cpp-netlib_pic)

I'm getting a linker error back because cpp-netlib is trying to link against the non-pic version of boost_network

/usr/bin/ld: ../third_party/cpp-netlib/libcpp-netlib_pic.a(client.cpp.o): \
    relocation R_X86_64_32 against `_ZTVN5boost7network4http4impl15normal_delegateE' \
    can not be used when making a shared object; recompile with -fPIC

Demangled name:

$ c++filt _ZTVN5boost7network4http4impl15normal_delegateE
vtable for boost::network::http::impl::normal_delegate

Boost Build:

This is all part of migrating our existing build system from boost-build to CMake.

The boost-build Jamfiles work fine.

Jamroot:

variant pic : release : <cxxflags>-fPIC ;

cpp-netlib/Jamfile:

lib cpp-netlib 
: [ glob src/*.cpp ]
;

foo/Jamfile:

shared-lib foo
: [ glob *.cpp ]
  /ext/cpp-netlib//cpp-netlib/<variant>pic
: <link>shared
  <cxxflags>-fPIC
;

This works.

Note there is no mention of boost::network anywhere, although there is a subfolder in cpp-netlib/boost/library, but it contains headers only.


Question:

How do I tell CMake that cpp-netlib_pic needs to use the pic version of boost_network?

Upvotes: 2

Views: 1510

Answers (1)

Steve Lorimer
Steve Lorimer

Reputation: 28659

This is just a case of not using the correct syntax

Instead of specifying the property:

set_property(TARGET cpp-netlib_pic PROPERTY POSITION_INDEPENDENT_CODE)

You have to turn it ON:

set_property(TARGET cpp-netlib_pic PROPERTY POSITION_INDEPENDENT_CODE ON)

Upvotes: 2

Related Questions