18

I have recently installed XUbuntu 11.10 64bit, but I am having problem compiling the most simple pthread example.

Here is the code pthread_simple.c:

#include <stdio.h>
#include <pthread.h> 
main()  {
  pthread_t f2_thread, f1_thread; 
  void *f2(), *f1();
  int i1,i2;
  i1 = 1;
  i2 = 2;
  pthread_create(&f1_thread,NULL,f1,&i1);
  pthread_create(&f2_thread,NULL,f2,&i2);
  pthread_join(f1_thread,NULL);
  pthread_join(f2_thread,NULL);
}
void *f1(int *x){
  int i;
  i = *x;
  sleep(1);
  printf("f1: %d",i);
  pthread_exit(0); 
}
void *f2(int *x){
  int i;
  i = *x;
  sleep(1);
  printf("f2: %d",i);
  pthread_exit(0); 
}

And here is the compile command

gcc -lpthread pthread_simple.c

The results:

lptang@tlp-linux:~/test/test-pthread$ gcc -lpthread pthread_simple.c 
/tmp/ccmV0LdM.o: In function `main':
pthread_simple.c:(.text+0x2c): undefined reference to `pthread_create'
pthread_simple.c:(.text+0x46): undefined reference to `pthread_create'
pthread_simple.c:(.text+0x57): undefined reference to `pthread_join'
pthread_simple.c:(.text+0x68): undefined reference to `pthread_join'
collect2: ld returned 1 exit status

Does anyone know what's causing the problem?

chtlp
  • 283
  • 1
  • 2
  • 5

3 Answers3

31

In the latest versions of gcc compiler require that libraries follow the object or source files.

So to compile this it should be:

gcc pthread_sample.c -lpthread

Normally though pthread code is compiled this way:

gcc -pthread pthread_sample.c
Karlson
  • 5,845
  • 32
  • 51
  • 1
    @Karlson Can you please explain why just including the `pthread.h` file is not enough for gcc to resolve the references? – Quazi Irfan Dec 31 '16 at 21:58
  • 3
    @iamcreasy Because declaration is not the same as definition. The program needs to know where the code executing a particular function is. – Karlson Dec 31 '16 at 23:24
  • Sorry, could you please tell us what's the difference between `-pthread` and `-lpthread`. Some tutorial add `-l` some don't, why? – Paris Qian Sen Jun 02 '21 at 13:49
1
gcc -o exectable_namme pthread_sample.c -lpthread
chaos
  • 47,463
  • 11
  • 118
  • 144
  • 4
    It would be helpful to [edit your answer](http://unix.stackexchange.com/posts/244330/edit) to explain why this is different from the already accepted answer. – roaima Nov 20 '15 at 11:17
0

compile code using following command

gcc filename.c -lpthread -lrt
PersianGulf
  • 10,728
  • 8
  • 51
  • 78
  • 3
    Hi! It would be helpful if you could edit your answer to explain why it works, and to highlight why you think it adds something the already accepted answer doesn't cover. – dhag Apr 08 '15 at 04:28