title: How to include all objects of an archive in a shared object?
body: <p>When compiling our project, we create several archives (static libraries), say <code>liby.a</code> and <code>libz.a</code> that each contains an object file defining a function <code>y_function()</code> and <code>z_function()</code>. Then, these archives are joined in a shared object, say <code>libyz.so</code>, that is one of our main distributable target.</p>
  
  <pre><code>g++  -fPIC  -c -o y.o y.cpp
  ar cr liby.a y.o
  g++  -fPIC  -c -o z.o z.cpp
  ar cr libz.a z.o
  g++ -shared -L. -ly -lz -o libyz.so
  </code></pre>
  
  <p>When using this shared object into the example program, say <code>x.c</code>, the link fails because of an undefined references to functions <code>y_function()</code> and <code>z_function()</code>.</p>
  
  <pre><code>g++ x.o -L. -lyz -o xyz
  </code></pre>
  
  <p>It works however when I link the final executable directly with the archives (static libraries).</p>
  
  <pre><code>g++ x.o -L. -ly -lz -o xyz
  </code></pre>
  
  <p>My guess is that the object files contained in the archives are not <em>linked</em> into the shared library because they are not used in it. How to force inclusion?</p>
  
  <p>Edit:</p>
  
  <p>Inclusion can be forced using --whole-archive <code>ld</code> option. But if results in compilation errors:</p>
  
  <pre><code>g++ -shared '-Wl,--whole-archive' -L. -ly -lz -o libyz.so
  /usr/lib/libc_nonshared.a(elf-init.oS): In function `__libc_csu_init':
  (.text+0x1d): undefined reference to `__init_array_end'
  /usr/bin/ld: /usr/lib/libc_nonshared.a(elf-init.oS): relocation R_X86_64_PC32 against undefined hidden symbol `__init_array_end' can not be used when making a shared object
  /usr/bin/ld: final link failed: Bad value
  </code></pre>
  
  <p>Any idea where this comes from?</p>