J'ai récupéré la démo suivante sur le web à l'adresse 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);
}
Mais lorsque je la compile sur ma machine (sous Ubuntu Linux 9.04), j'obtiens l'erreur suivante :
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
Cela n'a aucun sens pour moi, car l'en-tête inclut pthread.h
, qui devrait avoir la fonction pthread_create
. Avez-vous une idée de ce qui ne va pas ?
Les deux réponses à cette question jusqu'à présent sont incorrectes.
Pour Linux, la commande correcte est :
gcc -pthread -o term term.c
En général, les bibliothèques doivent suivre les sources et les objets sur la ligne de commande, et -lpthread
n'est pas une "option" ;, c'est une spécification de bibliothèque. Sur un système avec seulement libpthread.a
installé,
gcc -lpthread ...
ne se liera pas.