CMake does not turn on CMAKE_POSITION_INDEPENDENT_CODE when BUILD_SHARED_LIBS=ON
I got a bug report for HelFEM, https://github.com/susilehtola/HelFEM, saying that the build fails when BUILD_SHARED_LIBS=ON
.
The CMake files used by the project are very simple, and just employ add_library()
to create the libraries, without definining STATIC
or SHARED
.
When BUILD_SHARED_LIBS=ON
, these libraries are generated in dynamic form. However, CMake does not turn on position independent code and the link phase fails with several errors of the type
relocation R_X86_64_32S against `.rodata' can not be used when making a shared object; recompile with -fPIC
I've been able to work around the issue by turning on position independent code whenever BUILD_SHARED_LIBS
is enabled
if(BUILD_SHARED_LIBS)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
endif()
However, I think that this should happen automatically for the library targets that are compiled as dynamic libraries due to BUILD_SHARED_LIBS
; this would be the logical behavior according to the defaults for SHARED
targets https://cmake.org/cmake/help/v3.9/prop_tgt/POSITION_INDEPENDENT_CODE.html