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!

Griwes
  • 8,805
  • 2
  • 43
  • 70
Mike
  • 425
  • 2
  • 6
  • 8
  • 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?). – David Schwartz Jun 20 '12 at 00:25
  • 1
    Undefined reference is **linker**, not **compiler** error. – Griwes Jun 20 '12 at 00:33
  • 1
    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*. – ephemient Jun 20 '12 at 00:38

1 Answers1

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

Ben Jackson
  • 90,079
  • 9
  • 98
  • 150
  • 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`? Thanks – Mike Jun 20 '12 at 00:41
  • 1
    @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? – abarnert Jun 20 '12 at 00:44
  • @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… – abarnert Jun 20 '12 at 00:46