For my project, I'd like to be able to build the core c++ libraries as static libraries, but compile the main JNI (Java glue) as a shared library (needs to be loaded at runtime by JVM). In pseudo code this would be:
project(foo CXX)
add_library(foo1 foo1.cxx)
add_library(foo2 foo2.cxx)
add_library(foojni SHARED foojni.cxx)
target_link_libraries(foojni LINK_PRIVATE foo1 foo2)
Right now on x86_64, it fails with the following error message:
relocation R_X86_64_32 against `.rodata' cannot be used when making a shared object; recompile with -fPIC
Obviously the simple fix is:
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
However I'd prefer a less invasive solution for my users, instead, I am thinking of:
if(BUILD_JNI)
if(NOT BUILD_SHARED_LIBS)
if(CMAKE_COMPILER_IS_GNUCXX)
if(CMAKE_ARCHITECTURE STREQUAL "x86_64") # FIXME !!
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
endif()
endif()
endif()
endif()
Of course, the following line does not work (no such thing as CMAKE_ARCHITECTURE
).
if(CMAKE_ARCHITECTURE STREQUAL "x86_64") # FIXME !!
Since detecting architecture seems quite hard (see) and even if I was able to do so, I do not know what are the requirements for ppc64el, mips or m68k (insert any exotic system here). So I'd like to know if there is a simple way to query cmake about:
- Does my compiler supports linking shared library to static library?
- Ideally: Dump the missing compiler flags required to achieve such linking step.
I know of:
if(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64")
But as explained in the link above, this will not work for cross-compilation.
Update: The question is obviously not how to set -fPIC
(or equivalent) compiler flag, but when do I need to set it.