Error with sem_init () function in Linux

2

I'm trying to solve a problem with semáforos , but when I try to use the sem_init() function I get an error saying that there is undefined reference, Can you tell me why?

I have the semáforos library included.

Code (C):

#include<semaphore.h>
#include<sys/sem.h>

int pos_escrita;
int pos_leitura;

int buffer[10]; //capacidade para 10

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t vazio;
sem_t cheio;

// IDs das threads
int id_produtores[100];
int id_consumidores[10];

void init()
{
    sem_init(&vazio, 0, 10);
    sem_init(&cheio, 0, 0);
    pos_escrita = 0;
    pos_leitura = 0;
}

int main()
{
    int i;
    init();
    pthread_t threads[2]; // nº de threads

    for(i=0; i<10;i++)
    {
    }

    printf("\n");
    return 0;
}

The displayed error was:

  

/tmp/ccTcI1EU.o: In function init ': f.c :(. text + 0x1e): undefined   reference to sem_init 'f.c :(. text + 0x3a): undefined reference to   sem_init 'collect2: ld returned 1 exit status

    
asked by anonymous 27.01.2016 / 23:54

2 answers

2

According to the SO post: Undefined Reference issues using Semaphores

If you are on a Linux system, you need to include the library pthreads and rt (as documented in Synchronizing Threads with POSIX Semaphores during the compile and link processes because the error demonstrates that the function implementation was not found when linking the program.

Example:

gcc -o arquivo_saida arquivo_fonte.c -lpthread -lrt

Note: In the above command, the library names should come after the .c file (s).

    
28.01.2016 / 00:27
1

The error you got is a linkage error. Your C code is correct and the functions you use are declared in the ".h" files that you include. However, at the time of generating the executable your compiler is not finding the implementation of the semaphore functions.

The solution is to add the -lpthread flag when compiling your program.

    
28.01.2016 / 00:17