title: Force linking to pthread with G++
body: <p>I am having some trouble with one of my projects. It seems that I link towards a library that requires pthread symbols, but the library itself is not linked with pthread. The symptoms is that the program segfaults when I try to run it. I ran:</p>
  
  <pre><code>LD_DEBUG=all ./my_program
  </code></pre>
  
  <p>and found out it segfaults while looking for pthread_create. The program runs if I force preload of pthread using this command:</p>
  
  <pre><code>LD_PRELOAD=/lib/x86_64-linux-gnu/libpthread.so.0 ./my_program
  </code></pre>
  
  <p>To solve this problem I thought I'd just link my_program with pthread in the build script using -lpthread. That didn't work so I tried -pthread. Didn't work either. I was able to reproduce this to the bare minimal:</p>
  
  <pre><code>echo "int main() { return 0; }" | g++ -x c++ - -pthread -lpthread -o my_program &amp;&amp; ldd my_program
  linux-vdso.so.1 =&gt;  (0x00007ffe4fd08000)
  libc.so.6 =&gt; /lib/x86_64-linux-gnu/libc.so.6 (0x00007f150ca5c000)
  /lib64/ld-linux-x86-64.so.2 (0x000055ac8c275000)
  </code></pre>
  
  <p>As you can see from the output of ldd, my_program is not linked with pthread. I suspected that this happens because g++ understands I am not actually using any symbols from pthread and does not link with it. So I tried adding a call to pthread_create:</p>
  
  <pre><code>echo -e "#include &lt;pthread.h&gt;\n int main() { pthread_create(0,0,0,0); return 0; }" | g++ -x c++ - -pthread -o my_program &amp;&amp; ldd my_program
  &lt;stdin&gt;: In function ‘int main()’:
  &lt;stdin&gt;:2:37: warning: null argument where non-null required (argument 1) [-Wnonnull]
  &lt;stdin&gt;:2:37: warning: null argument where non-null required (argument 3) [-Wnonnull]
  linux-vdso.so.1 =&gt;  (0x00007ffd977f9000)
  libpthread.so.0 =&gt; /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fafe1bb6000)
  libc.so.6 =&gt; /lib/x86_64-linux-gnu/libc.so.6 (0x00007fafe17f1000)
  /lib64/ld-linux-x86-64.so.2 (0x0000563ee0002000)
  </code></pre>
  
  <p>Please ignore the warnings, I know the call to pthread_create is bogus. The point is that now it actually links with pthread. </p>
  
  <p>So my question is: Is there anyway to force g++ to link with something (in this case pthread) without adding dummy code using the symbols?</p>