Search code examples
cshared-librariesldicc

Why do I have to explicitly link to pthreads in my main.c compilation when my main.c does not use pthreads?


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?


Solution

  • 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.