-1

Possible Duplicate:
undefined reference to pthread_create in linux (c programming)

There is the following program:

void *thread(void *vargp);

int main() {
  pthread_t tid;

  pthread_create(&tid, NULL, thread, NULL);
  exit(0);
}

/* thread routine */
void *thread(void *vargp) {
  sleep(1);
  printf("Hello, world!\n");
  return NULL;
}

I am supposed to correct it. I allready added the includes left:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

But I still get the following errors:

/tmp/ccHwCS8c.o: In function `main':
1.c:(.text+0x29): undefined reference to `pthread_create'
collect2: ld returned output state 1

I tried adding -lpthread with the compiler like the answers sayd but I still get this error codes:

@lap:~$ gcc -Wall -lpthread 1.c -o uno

/tmp/ccl19SMr.o: In function `main':
1.c:(.text+0x29): undefined reference to `pthread_create'
collect2: ld returned exit state 1
Community
  • 1
  • 1
Alexander Meise
  • 1,328
  • 2
  • 15
  • 31

3 Answers3

3

In your compilation/linking add "-lpthread".

eyalm
  • 3,366
  • 19
  • 21
2

You need to explicitly mention the -pthread option while compiling. Without this linker is not able to find the reference of pthread library. Do like this :

gcc -Wall -pthread test.c -o test.out

Omkant
  • 9,018
  • 8
  • 39
  • 59
2

You need to compile it with -lpthread flag in order to link the libpthread to your executable.

Also you should to add the pthread_join() function in order to let your main thread to wait for the new thread ending. In your current code you will not see the Hello Worldbecause main thread ending will cause all son threads exiting.

Alex
  • 9,891
  • 11
  • 53
  • 87
  • You are right I dont see `Hello World` at all. I will add pthread_join() but I dont know what arguments to add. – Alexander Meise Dec 09 '12 at 18:02
  • 1
    @Rkan Please follow the link: http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_join.3.html – Alex Dec 09 '12 at 18:06