Referencia indefinida a pthread_create en Linux

He cogido la siguiente demo de la web 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);
}

Pero cuando lo compilo en mi máquina (corriendo Ubuntu Linux 9.04) me da el siguiente error:

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

Esto no tiene ningún sentido para mí, porque la cabecera incluye pthread.h, que debería tener la función pthread_create. ¿Alguna idea de qué está fallando?

Las dos respuestas a esta pregunta hasta ahora son incorrectas; Para Linux el comando correcto es:

gcc -pthread -o term term.c

En general, las bibliotecas deben seguir las fuentes y los objetos en la línea de comandos, y lpthread no es una "opción", es una especificación de la biblioteca. En un sistema con sólo libpthread.a instalado,

gcc -lpthread ...

fallará al enlazar.

Comentarios (7)

Es necesario utilizar la opción -lpthread con gcc.

Comentarios (2)

solo necesitas añadir "pthread" en propriedades=>C/C++ build=>GCC C++ Linker=>Libraries=> parte superior "Libraries(-l)". eso es todo

Comentarios (0)