Take the 2-minute tour ×

In Linux, I have a shared library I made that uses pthreads and a main.c that does not.

libpthread.so shows up in an ldd of my shared library, which is correct.

$ ldd libmapreduce.so.1.0 
    linux-gate.so.1 =>  (0x0067d000)
    libpthread.so.0 => /lib/libpthread.so.0 (0x0058c000)

But when I compile and link my main.c that does not use pthreads to my shared library that does, I see:

$ icc -Wall -o main main.c -lmapreduce
    /opt/intel/Compiler/11.1/046/lib/ia32/libiomp5.so: undefined reference to `pthread_atfork'

Adding -lpthread to my compile command, i.e.,

$ icc -Wall -o main main.c -lmapreduce -lpthread

resolves the undefined reference.

Why do I need to explicitly link to libpthread when my main.c does not use it and my shared library already has libpthread linked in?

share|improve this question
add comment

2 Answers

In order to create an executable or DLL you need to link in the transitive closure of all dependencies in your program. Because main.c links in sharedlib you must also link in all dependencies of sharedlib which includes pthreads.

share|improve this answer
Thanks! I have somehow never managed to run into this before... –  David Pointer Mar 13 '12 at 18:33
If the shared libs which need pthread were linked correctly, you should not need it on the main program's link command line. I suspect one or more libs are linked with the pthread symbols being treated as undefined/provided by main program, rather than with a reference to libpthread. –  R.. Mar 13 '12 at 19:21
@R.. Thanks, you answered the question I did not know how to state. I'll keep digging. –  David Pointer Mar 13 '12 at 20:11
I think @R.. 's comment is the correct answer to this question. –  Pavan Manjunath Mar 14 '12 at 14:01
add comment
up vote 0 down vote accepted

Thank you R.. and Pavan Manjunath, for encouraging me to keep digging.

The link step for the shared library libmapreduce.so looked like:

icc -shared -g -o libmapreduce.so.1.0 map.o map_wrp.o -openmp [...] -lpthread -ldl

That -openmp link flag was not needed and in fact introduced the undefined reference to pthread_atfork. The undefined reference to pthread_atfork did not show up until I tried to link a main.c with the shared library libmapreduce.so. Re-creating libmapreduce.so without the -openmp flag removed the problem.

share|improve this answer
add comment

Your Answer


