简体   繁体   中英

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, ie,

$ 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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM