bofjas
bofjas

Reputation: 1206

Force linking to pthread with G++

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:

LD_DEBUG=all ./my_program

and found out it segfaults while looking for pthread_create. The program runs if I force preload of pthread using this command:

LD_PRELOAD=/lib/x86_64-linux-gnu/libpthread.so.0 ./my_program

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:

echo "int main() { return 0; }" | g++ -x c++ - -pthread -lpthread -o my_program && ldd my_program
linux-vdso.so.1 =>  (0x00007ffe4fd08000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f150ca5c000)
/lib64/ld-linux-x86-64.so.2 (0x000055ac8c275000)

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:

echo -e "#include <pthread.h>\n int main() { pthread_create(0,0,0,0); return 0; }" | g++ -x c++ - -pthread -o my_program && ldd my_program
<stdin>: In function ‘int main()’:
<stdin>:2:37: warning: null argument where non-null required (argument 1) [-Wnonnull]
<stdin>:2:37: warning: null argument where non-null required (argument 3) [-Wnonnull]
linux-vdso.so.1 =>  (0x00007ffd977f9000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fafe1bb6000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fafe17f1000)
/lib64/ld-linux-x86-64.so.2 (0x0000563ee0002000)

Please ignore the warnings, I know the call to pthread_create is bogus. The point is that now it actually links with pthread.

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?

Upvotes: 2

Views: 2201

Answers (1)

Employed Russian
Employed Russian

Reputation: 213375

Is there anyway to force g++ to link with something (in this case pthread) without adding dummy code using the symbols?

Try this:

echo "int main() { return 0; }" |
g++ -x c++ - -o my_program -Wl,--no-as-needed -lpthread -Wl,--as-needed

Upvotes: 2

Related Questions