Search code examples
cthread-synchronization

Undefined reference to all 'sem' and 'pthread' functions upon compilation


I'm using the gcc to compile this c program that just relies on 2 created thread, one to increment a counter, the second reads the counter and subtracts a random (0-9) value from the counter, and then displays the counter's value, using a Semaphore to access it. Still upon compilation I'm facing lots of ' Undefined reference to sem_init/sem_wait/sem_post/pthread_create/..etc' I don't know why although I associated them headers in my program.

I'm using 'gcc -o prog prog.c'to compile my program.

#include<semaphore.h>
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

int counter=0;
int run=1;
sem_t mutex;

void * increm();

void * decrem();


void main()
{       sem_t mutex;
    sem_init(&mutex,0,1);
    pthread_t t1,t2;
    pthread_create(&t1,NULL,increm,NULL);
    pthread_create(&t2,NULL,decrem,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
sem_destroy(&mutex);
}
void * increm()
{  while(run)
    {sem_wait(&mutex);
            counter++;
            sem_post(&mutex);
    }
    pthread_exit(NULL);
}

 void * decrem()
{ int i=25;

    while(i>0)
    {sem_wait(&mutex);
            counter-=(rand()%10);
           printf("Counter value : %d \n",counter);
            i--;
            sem_post(&mutex);
    }
    run=0;
    pthread_exit(NULL);
 }

Solution

  • [...] upon compilation I'm facing lots of ' Undefined reference to sem_init/sem_wait/sem_post/pthread_create/..etc' I don't know why although I associated them headers in my program.

    I'm using 'gcc -o prog prog.c'to compile my program.

    With GCC, you should pass the -pthread option to gcc when you compile and when you link a program that uses pthreads functions:

    gcc -pthread -o prog prog.c
    

    At minimum, this will cause the needed library(-ies) to be included in the link, but in principle, it may have effects on code generation as well in some versions of GCC and on some platforms.

    See also Significance of -pthread flag when compiling, Difference between -pthread and -lpthread while compiling, and many others.