with -lpthread, g++ compiler error, "undefined reference to " semaphore calls such as `sem_open'
Asked Answered
M

1

6

I am new to posix thread library, and I tried to compile a sample code from a tutorial with:

g++ -lpthread agreement.cpp -o agreement

however I was not able to compile the code and got the following error message:

a3q2.cpp:(.text+0x7e): undefined reference to `sem_open'
a3q2.cpp:(.text+0xab): undefined reference to `sem_wait'
a3q2.cpp:(.text+0x290): undefined reference to `sem_post'
a3q2.cpp:(.text+0x2af): undefined reference to `sem_close'
a3q2.cpp:(.text+0x2bb): undefined reference to `sem_unlink'
collect2: ld returned 1 exit status
make: *** [a3q2_exe] Error 1

I am aware that -lpthread is needed for compilation to work, but is there any other options i might need to solve the problem? if not how do I have to install the "proper" pthread library?

Thanks for your help!

Musselman answered 20/6, 2012 at 0:22 Comment(3)
You want -pthread, not -lpthread. Compiling with pthreads support may require more than just a library. Your platform may require -lrt for semaphores (did you check the man page?).Latvia
Undefined reference is linker, not compiler error.Fridell
Also, objects (and archives) providing symbols must be ordered after objects using those symbols when linking. It may not matter here, but get into the habit of putting -lfoo towards the end of the command, not the start.Wizard
S
13

You want the compile option -pthread (if you are really using pthreads). If you just need those functions they are in librt so use -lrt

Selfassured answered 20/6, 2012 at 0:28 Comment(3)
thanks a ton, i was able to solve the problem with -pthread but could you elaborate on why that is? and whats the difference between -lpthread and -pthread? ThanksMusselman
@Mike: If you look at the manpage for gcc, -pthread: "Adds support for multithreading with the pthreads library. This option sets flags for both the preprocessor and linker." The exact flags may differ from platform to platform; on your system, it may be something like "-D__PTHREADS -lpthread -lrt", which means that just passing "-lpthread" isn't sufficient. You could figure out exactly what it maps to on every platform you care about and pass that instead, by why?Bolden
@Mike: On top of that, some other compilers (I believe icc) in "gcc compatibility mode" may also use -pthread to influence some code generation and/or optimization decisions, so if you end-run around it, you could end up with code that compiles and links but crashes 1 in a million times…Bolden

© 2022 - 2024 — McMap. All rights reserved.