Onduidelijke verwijzing naar pthread_create in Linux

Ik heb de volgende demo van het web geplukt van https://computing.llnl.gov/tutorials/pthreads/

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS     5

void *PrintHello(void *threadid)
{
   long tid;
   tid = (long)threadid;
   printf("Hello World! It's me, thread #%ld!\n", tid);
   pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc;
   long t;
   for(t=0; t<NUM_THREADS; t++){
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

Maar wanneer ik het compileer op mijn machine (waarop Ubuntu Linux 9.04 draait) krijg ik de volgende foutmelding:

corey@ubuntu:~/demo$ gcc -o term term.c
term.c: In function ‘main’:
term.c:23: warning: incompatible implicit declaration of built-in function ‘exit’
/tmp/cc8BMzwx.o: In function `main':
term.c:(.text+0x82): undefined reference to `pthread_create'
collect2: ld returned 1 exit status

Dit slaat nergens op, omdat de header pthread.h bevat, die de pthread_create functie zou moeten hebben. Iemand een idee wat er mis gaat?

Beide antwoorden op deze vraag tot nu toe zijn incorrect.
Voor Linux is het juiste commando:

gcc -pthread -o term term.c

In het algemeen moeten bibliotheken bronnen en objecten volgen op de commandoregel, en -lpthread is geen "option", het'is een bibliotheek specificatie. Op een systeem met alleen libpthread.a geïnstalleerd,

gcc -lpthread ...

zal het linken mislukken.

Commentaren (7)

Je moet de optie -lpthread gebruiken met gcc.

Commentaren (2)

je hoeft alleen maar "pthread" toe te voegen in proprieties=>C/C++ build=>GCC C++ Linker=>Libraries=> top part "Libraries(-l)". dat is het

Commentaren (0)