8
votes

I have this code:

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

void* cuoco(void* arg)
{
    fprintf(stderr,"Inizio codice cuoco\n");
    fprintf(stderr,"Fine codice cuoco\n");
    return NULL;
}

void* cameriere(void* arg)
{
    fprintf(stderr,"Inizio codice cameriere\n");
    fprintf(stderr,"Fine codice cameriere\n");
    return NULL;
}

void* cliente(void* arg)
{
    fprintf(stderr,"Inizio codice cliente\n");
    fprintf(stderr,"Fine codice cliente\n");
    return NULL;
}

int main(int argc, char* argv[])
{
    void* (*routine)(void*);
    routine=cuoco;
    pthread_t thread_cuoco,thread_cameriere,thread_cliente;
    pthread_create(&thread_cuoco,NULL,routine,NULL);
    return 0;
}

And in the compiler options I insert -lpthread
But it says:
"Undefined reference to pthread_create"
I use ubuntu 10.10, so I already have pthread library installed, I can't figure the reason of this error.

5
Show us how you compile your program. - cnicutar
How did you add the linker option & where? Which version of Code::Blocks? - another.anon.coward

5 Answers

30
votes

Use -lpthread as the last compiler flag.

example: gcc -o sample sample.c -lpthread

15
votes

Without seeing the compiler command, I suspect -lpthread is not at end. Libraries need to be placed at end of the compiler command:

gcc main.c -lpthread

However, use -pthread instead of -lpthread, as -pthread may add other settings (like defining the macro _REENTRANT for example).

5
votes

Use the following command:

gcc -pthread -o main main.c

0
votes

In Eclipse, you should add string pthread.

Project -> Properties -> C/C++ Build -> Settings -> Tool Settings -> GCC Linker -> Libraries -> Libraries (-l) -> Add -> pthread

After this, you can Build your project.

-2
votes

found the solution guys :D just go to settings >> compiler >> linker tab >>add lib

go to drive and go to lib folder and find x86_64_linux_gnu and find pthread enjoy :)