title: Remove dead code when linking static library into dynamic library
body: <p>Suppose I have the following files:</p>
  
  <p>libmy_static_lib.c:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  void func1(void){
      printf("func1() called from a static library\n");
  }
  void unused_func1(void){
      printf("printing from the unused function1\n");
  }
  void unused_func2(void){
      printf("printing from unused function2\n");
  }
  </code></pre>
  
  <p>libmy_static_lib.h:</p>
  
  <pre><code>void func(void);
  void unused_func1(void);
  void unused_func2(void);
  </code></pre>
  
  <p>my_prog.c:</p>
  
  <pre><code>#include "libmy_static_lib.h"
  #include &lt;stdio.h&gt;
  void func_in_my_prog()
  {
      printf("in my prog\n");
      func1();
  
  }
  </code></pre>
  
  <p>And here is how I link the library:</p>
  
  <pre><code># build the static library libmy_static_lib.a
  gcc -fPIC -c -fdata-sections --function-sections -c libmy_static_lib.c -o libmy_static_lib.o
  ar rcs libmy_static_lib.a libmy_static_lib.o
  
  # build libmy_static_lib.a into a new shared library
  gcc -fPIC -c ./my_prog.c -o ./my_prog.o
  gcc -Wl,--gc-sections -shared -m64 -o libmy_shared_lib.so ./my_prog.o -L. -l:libmy_static_lib.a
  </code></pre>
  
  <p>There are 2 functions in libmy_static_lib.c that are not used, and from <a href="https://stackoverflow.com/questions/6687630/how-to-remove-unused-c-c-symbols-with-gcc-and-ld">this post</a>, I think </p>
  
  <pre><code>gcc fdata-sections --function-sections
  </code></pre>
  
  <p>should create a symbol for each function, and </p>
  
  <pre><code>gcc -Wl,--gc-sections
  </code></pre>
  
  <p>should remove the unused symbols when linking</p>
  
  <p>however when I run </p>
  
  <pre><code>nm libmy_shared_lib.so
  </code></pre>
  
  <p>It is showing that these 2 unused functions are also being linked into the shared library.</p>
  
  <p>Any suggestions on how to have gcc remove the unused functions automatically?</p>
  
  <p>Edit:
  I am able to use the above options for gcc to remove the unused functions if I am linking a static library directly to executable. But it doesn't remove the unused functions if I link the static library to a shared library.</p>