CMake: Linking statically against libgcc and libstdc++ into a shared library
<p><strong>Problem:</strong></p>

<p>I am having difficulties linking glibcc/glibc++ into a shared library using CMake and GCC4.9 on my Ubuntu 16.04 installation.</p>

<p><strong>Additional conditions:</strong></p>

<p>Loading the shared library gives a problem om the Red Hat production environment(where I copy it to), I believe because it uses a different libstc++ version(error: GLIBCXX_3_4_20 not found). I do not have sudo rights and cannot upgrade the machine. </p>

<p>As I derived from <a href="http://www.trilithium.com/johan/2005/06/static-libstdc/" rel="noreferrer">this</a> blog, this <a href="https://stackoverflow.com/questions/2856438/how-can-i-link-to-a-specific-glibc-version">post</a>, I tried linking static linking against libgcc and libgc++ using:</p>

<pre><code>set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++ -static")
</code></pre>

<p>and againg using </p>

<pre><code>set(CMAKE_SHARED_LINKER_FLAGS "-static-libgcc -static-libstdc++ -static")
</code></pre>

<p>But that doesn't work. What <em>does</em> work is this CMake script: </p>

<pre><code>add_library(myLib SHARED ${SOURCE_FILES})
set(CMAKE_EXE_LINKER_FLAGS " -static")
target_link_libraries(myLib -static-libgcc -static-libstdc++)
</code></pre>

<p>This must be the wrong way of doing this, to my knowledge -static-libgcc and  -static-libstdc++ are linker options and not libraries...</p>

<p><strong>Question</strong>:
How do I link statically against -libgcc and -libstdc++ correctly?</p>

<p>Thanks in advance!</p>