Ho preso il seguente demo dal web da 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);
}
Ma quando lo compilo sulla mia macchina (con Ubuntu Linux 9.04) ottengo il seguente errore:
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
Questo non ha alcun senso per me, perché l'header include pthread.h
, che dovrebbe avere la funzione pthread_create
. Qualche idea su cosa sta andando storto?
Entrambe le risposte a questa domanda finora sono corrette; Per Linux il comando corretto è:
gcc -pthread -o term term.c
In generale, le librerie dovrebbero seguire i sorgenti e gli oggetti sulla linea di comando, e -lpthread
non è una "opzione", è una specifica di libreria. Su un sistema con solo libpthread.a
installato,
gcc -lpthread ...
non riuscirà a collegarsi.