Nedefinovaný odkaz na pthread_create v Linuxe

Z webu https://computing.llnl.gov/tutorials/pthreads/ som si vybral nasledujúcu ukážku

#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);
}

Ale keď ho skompilujem na svojom počítači (s Ubuntu Linux 9.04), dostanem nasledujúcu chybu:

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

Nedáva mi to zmysel, pretože hlavička obsahuje súbor pthread.h, ktorý by mal obsahovať funkciu pthread_create. Neviete, čo sa deje?

Obe doterajšie odpovede na túto otázku sú nesprávne.
Pre Linux je správny príkaz:

gcc -pthread -o term term.c

Vo všeobecnosti by knižnice mali nasledovať zdroje a objekty na príkazovom riadku a -lpthread nie je "voľba", je to'špecifikácia knižnice. V systéme s nainštalovanou iba libpthread.a,

gcc -lpthread ...

sa nepodarí prepojiť.

Komentáre (7)

Musíte použiť voľbu -lpthread s gcc.

Komentáre (2)

stačí pridať "pthread" v propries=>C/C++ build=>GCC C++ Linker=>Libraries=> horná časť "Libraries(-l)". to je všetko

Komentáre (0)