title: CMake: handle linking of shared library with static libraries
body: <p>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:</p>
  
  <pre class="lang-none prettyprint-override"><code>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)
  </code></pre>
  
  <p>Right now on x86_64, it fails with the following error message:</p>
  
  <pre><code>relocation R_X86_64_32 against `.rodata' cannot be used when making a shared object; recompile with -fPIC
  </code></pre>
  
  <p>Obviously the simple fix is:</p>
  
  <pre class="lang-none prettyprint-override"><code>set(CMAKE_POSITION_INDEPENDENT_CODE ON)
  </code></pre>
  
  <p>However I'd prefer a less invasive solution for my users, instead, I am thinking of:</p>
  
  <pre class="lang-none prettyprint-override"><code>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()
  </code></pre>
  
  <p>Of course, the following line does not work (no such thing as <code>CMAKE_ARCHITECTURE</code>).</p>
  
  <pre class="lang-none prettyprint-override"><code>if(CMAKE_ARCHITECTURE STREQUAL "x86_64") # FIXME !!
  </code></pre>
  
  <p>Since detecting architecture seems quite hard (<a href="https://stackoverflow.com/questions/11944060/how-to-detect-target-architecture-using-cmake">see</a>) 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:</p>
  
  <ul>
  <li>Does my compiler supports linking shared library to static library?</li>
  <li>Ideally: Dump the missing compiler flags required to achieve such linking step.</li>
  </ul>
  
  <hr>
  
  <p>I know of:</p>
  
  <pre class="lang-none prettyprint-override"><code>if(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64")
  </code></pre>
  
  <p>But as explained in the link above, this will not work for cross-compilation.</p>
  
  <hr>
  
  <p>Update: The question is obviously not <em>how</em> to set <code>-fPIC</code> (or equivalent) compiler flag, but <em>when</em> do I need to set it.</p>