Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sem_open() error: "undefined reference to sem_open()" on linux (Ubuntu 10.10)

So I am getting the error: "undefined reference to sem_open()" even though I have include 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;
}
like image 663
Robin Avatar asked Feb 06 '11 23:02

Robin


2 Answers

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

like image 191
Vlad H Avatar answered Sep 22 '22 12:09

Vlad H


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?

like image 45
William Pursell Avatar answered Sep 21 '22 12:09

William Pursell