6

I'm using eclipse on Fedora 17 (with GCC) and I have an undefined reference on pthread_create (), even if pthread.h is included and if I have -lpthread on the gcc build command line...

Here is my code, just in case

void* repair()
{
    int var;
    for ( var = 0; var < NB_ITER ; var += 2 )
    {
        printf( "PAIR : %d\n", var );
    }

return NULL;
} // pair

void exo03()
{
    pthread_t id1;
    pthread_create(&id1, NULL, &repair, NULL);
}

Thank you for helping :)

Carvallegro
  • 1,241
  • 4
  • 16
  • 24
  • 1
    You probably forgot you to link with pthread library. Add `-lpthread` in your compile command as the last one. – P.P Feb 27 '13 at 15:04
  • Can you provide a full example and exact note of compiler command + errors please? – simonc Feb 27 '13 at 15:05

2 Answers2

8

On linux, FreeBSD (and some other *nix flavors) you should use the compiler option -pthread and not trying to link with a pthread library.

For eclipse :

Eclipse is not configured to put the -pthread argument in the gcc compilation. To solve this, go to the Menu:

Project -> Properties

c/c++ build -> GCC C Compiler -> Miscellaneous

Add the “-pthread” argument into the beginning of the “Other Flags”

Also go to:

c/c++ build -> Settings -> GCC C Linker -> Libraries

And include the “pthread”library into the other libraries. Click Apply and rebuild the project. Pthreads must work now.

From man gcc:

-pthread : Adds support for multithreading with the pthreads library. This option sets flags for both the preprocessor and linker.

I found an explanation here :

In GCC, the -pthread (aka -pthreads) option manages both the compiler preprocessor /and/ linker to enable compilation with Posix threads. The preprocessor will define/enable/use Posix threads versions of some macros (or perform conditional compilation to enable Posix threads logic), and the linker will specifically link the resultant object against libpthread

However, -lpthread simply tells the linker to attempt to resolve any external references against the libpthread library, in the same way that -lm tells the linker to attempt to resolve any external references against the libm library. For -lpthread, your code might not contain external references to libpthread, even if you wrote Posix thread code, because the critical macros haven't been switched on.

Community
  • 1
  • 1
Cédric Julien
  • 78,516
  • 15
  • 127
  • 132
6

Have you linked to libpthread?

$> gcc ... -lpthread
bash.d
  • 13,029
  • 3
  • 29
  • 42