Search code examples
csolarislinker-errorssemaphorebuild-error

Can't compile code with semaphore under Solaris?


I have written some code which compiles fine under linux but on Solaris I am given some compiling errors. I use gcc test_compile.c -o tes -pthreads to compile.

#include <semaphore.h>

int main(){
    sem_t semaphore;
    sem_init(&semaphore, 0, 0);
    return 0;
}

Gives me

itchy:~/edu/sysprog> gcc test_compile.c -o tes -pthreads
Undefined                       first referenced
 symbol                             in file
sem_init                            /var/tmp//ccUiSK6A.o
ld: fatal: Symbol referencing errors. No output written to tes

I am not sure what's going on. I tryied replacing sem_init with sema_init and it compiles(saw that somewhere online). However that would mean that I must go through my whole code and replace sem with sema. Isn't there a simpler solution? And what does it really mean?


Solution

  • You need to link with the realtime extensions library librt:

    gcc test_compile.c -o tes -lrt -pthreads
    

    This is documented in the man page for sem_init(3RT):

    SYNOPSIS
         cc [ flag... ] file... -lrt [ library... ]
         #include <semaphore.h>
    
         int sem_init(sem_t *sem, int pshared, unsigned int value);