Undefined reference to pthread_create in Linux

2018-12-31 15:08发布

问题:

I picked up the following demo off the web from 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);
}

But when I compile it on my machine (running Ubuntu Linux 9.04) I get the following 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

This doesn\'t make any sense to me, because the header includes pthread.h, which should have the pthread_create function. Any ideas what\'s going wrong?

回答1:

Both answers to this question so far are incorrect.
For Linux the correct command is:

gcc -pthread -o term term.c

In general, libraries should follow sources and objects on command line, and -lpthread is not an \"option\", it\'s a library specification. On a system with only libpthread.a installed,

gcc -lpthread ...

will fail to link.



回答2:

in eclipse

properties->c/c++Build->setting->GCC C++ linker->libraries in top part add \"pthread\"



回答3:

Acutally, it gives several examples of compile commands used for pthreads codes are listed in the table below, if you continue reading the following tutorial:

https://computing.llnl.gov/tutorials/pthreads/#Compiling

\"enter



回答4:

Compile it like this : gcc demo.c -o demo -pthread



回答5:

Running from the Linux terminal, what worked for me was compiling using the following command (suppose the c file I want to compile is called test.c):

gcc -o test test.c -pthread

Hope it helps somebody!



回答6:

You need to use the option -lpthread with gcc.



回答7:

you need only Add \"pthread\" in proprieties=>C/C++ build=>GCC C++ Linker=>Libraries=> top part \"Libraries(-l)\". thats it



回答8:

In Anjuta, go to the Build menu, then Configure Project. In the Configure Options box, add:

LDFLAGS=\'-lpthread\'

Hope it\'ll help somebody too...



回答9:

Sometimes, if you use multiple library, check the library dependency. (e.g. -lpthread -lSDL... <==> ... -lSDL -lpthread)



回答10:

If you are using cmake, you can use:

add_compile_options(-pthread)

Or

SET(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -pthread\")