Error with sem_init() function on Linux

Asked

Viewed 525 times

2

I’m trying to solve a problem with semáforos, but when I try to use the function sem_init() I get an error saying there’s an indefinite reference, can tell me why?

I have the library of semáforos 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 error presented was:

/tmp/ccTcI1EU: 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

  • Try to put -lrt or -lpthread when compiling: gcc codigo.c -lpthread -o codigo

2 answers

2


According to the post in the OS (in English): Undefined Reference issues using Semaphores

If you are on a Linux system, you need to include the library pthreads and rt (as the documentation in Synchronizing Threads with POSIX Semaphores) during the build and link processes, as the error shows 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, library names must come after the file(s)) .c.

1

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.