15

So I am getting the error: "undefined reference to sem_open()" even though I have included the <semaphore.h> header. The same thing is happening for all my pthread function calls (mutex, pthread_create, etc). Any thoughts? I am using the following command to compile:

g++ '/home/robin/Desktop/main.cpp' -o '/home/robin/Desktop/main.out'

#include <iostream>
using namespace std;
#include <pthread.h>
#include <semaphore.h>
#include <fcntl.h>

const char *serverControl = "/serverControl";
sem_t* semID;

int main ( int argc, char *argv[] )
{
    //create semaphore used to control servers
    semID = sem_open(serverControl,O_CREAT,O_RDWR,0);
    return 0;
}
Rachid K.
  • 4,490
  • 3
  • 11
  • 30
Robin
  • 737
  • 2
  • 10
  • 23

3 Answers3

24

You need link with pthread lib, using -lpthread option.

Vlad H
  • 3,629
  • 1
  • 19
  • 13
6

Including the header does not tell ld about the library. You need to add -lrt to your compilation command line. For threading, you need either -lpthread or -pthread, depending on your platform.

The library is not the header. The header is not the library. This is an important distinction. See What's the difference between a header file and a library?

Community
  • 1
  • 1
William Pursell
  • 204,365
  • 48
  • 270
  • 300
3

The working option in Ubuntu is -lpthread. But if you work on suse or other systems the correct option is -lrt. Also the book Linux Programmin Interface mentions -lrt as the correct option.

Sanjay Bhosale
  • 685
  • 2
  • 8
  • 18