title: Including objects to a shared library from a C++ archive (.a)
body: <p>I am trying to include some object files into a shared library I am building.  Take the following command (things in [ETC] have been omitted for brevity):</p>
  
  <blockquote>
    <p>/usr/bin/c++ -fPIC -std=c++14 -pthread -Iinclude/ext/liveMedia -Iinclude/ext/groupsock [ETC] -g -shared -Wl,-soname,libValkka.so -o lib/libValkka.so CMakeFiles/Valkka.dir/src/avthread.cpp.o CMakeFiles/Valkka.dir/src/opengl.cpp.o [ETC] CMakeFiles/Valkka.dir/src/decoders.cpp.o -lX11 -lGLEW -lGLU -lGL -Wl,--whole-archive lib/libavcodec.a -Wl,--no-whole-archive</p>
  </blockquote>
  
  <p>So basically I am just creating a shared library where most of the objects come from my own source code (i.e. CMakeFiles/Valkka.dir/src/*.o), but some of them come from an external static library, located at "lib/libavcodec.a".  I get the following error:</p>
  
  <blockquote>
    <p>/usr/bin/ld: lib/libavcodec.a(h264_cabac.o): relocation R_X86_64_PC32 against symbol 'ff_h264_cabac_tables' can not be used when making a shared object; recompile with -fPIC
    /usr/bin/ld: final link failed: Bad value
    collect2: error: ld returned 1 exit status</p>
  </blockquote>
  
  <p>But that is so untrue!  I can extract "libavcodec.a" with</p>
  
  <pre><code>ar x libavcodec.a
  </code></pre>
  
  <p>And after that check that</p>
  
  <pre><code>readelf --relocs h264_cabac.o | egrep '(GOT|PLT|JU?MP_SLOT)' 
  </code></pre>
  
  <p>does give some **it:</p>
  
  <blockquote>
    <p>00000000175d  003100000004 R_X86_64_PLT32    0000000000000000 __stack_chk_fail - 4
    000000001926  003100000004 R_X86_64_PLT32    0000000000000000 __stack_chk_fail - 4</p>
    
    <p>...</p>
  </blockquote>
  
  <p>As does </p>
  
  <pre><code>objdump -r h264_cabac.o | grep -i "relocation"
  </code></pre>
  
  <p>So, indeed, the object files in "libavcodec.a" have been compiled to get PIC (position independent code).</p>
  
  <p>Why does the linker believe otherwise!?</p>
  
  <p>Related links:</p>
  
  <p><a href="https://stackoverflow.com/questions/2763988/how-to-include-all-objects-of-an-archive-in-a-shared-object">How to include all objects of an archive in a shared object?</a></p>
  
  <p><a href="https://stackoverflow.com/questions/7935421/linking-archives-a-into-shared-object-so">Linking archives (.a) into shared object (.so)</a></p>
  
  <p><a href="https://stackoverflow.com/questions/3507296/is-there-a-way-to-determine-that-a-a-or-so-library-has-been-compiled-as-positi">Is there a way to determine that a .a or .so library has been compiled as position indepenent code?</a></p>
  
  <p><a href="https://stackoverflow.com/questions/1340402/how-can-i-tell-with-something-like-objdump-if-an-object-file-has-been-built-wi/1351771#1351771">How can I tell, with something like objdump, if an object file has been built with -fPIC?</a></p>