1

I try to compile a c file which was include threads. but i tried to compile normal way like this

gcc -o thread thread.c -Wall

But it gives an error. but I tried to compile like this way

gcc -pthread -o thread thread.c -Wall

It worked. what is the reason of this and -pthread flag what will do? my C code below

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

void *thread_function(void *arg)
{
    int a;
    for(a=0;a<10; a++)
    {
    printf("Thread says hi!\n");
    sleep(2);
    }
    return NULL;
}

int main(void)
{
    pthread_t mythread;
    if ( pthread_create( &mythread, NULL, thread_function, NULL) )
    {
        printf("error creating thread.");
        abort();
    }
    if ( pthread_join ( mythread, NULL ) )
    {
    printf("error joining thread.");
    abort();
    }
    printf("Main thread says hi!\n");
    exit(0);
}
too honest for this site
  • 12,050
  • 4
  • 30
  • 52
kgdc
  • 166
  • 4
  • 13
  • You should look at: https://stackoverflow.com/questions/23250863/difference-between-pthread-and-lpthread-while-compiling. Essentially, you need to tell the compiler to link in pthread library – Mike R Sep 04 '17 at 13:30
  • What's particularily unclear about the gcc documentation? – too honest for this site Sep 04 '17 at 13:31
  • Read this for reference [https://randu.org/tutorials/threads/](https://randu.org/tutorials/threads/) – Dhruvil Vaghela Sep 04 '17 at 13:32
  • Actually, both -pthread and -lpthread are platform-dependent. Some standard C libraries, e.g., Android Bionic, provide internal implementations of `pthread_create()`, etc. Stop me if I'm not helping ;) – Kevin Boone Sep 04 '17 at 13:41
  • I didn't see those links. there are lot of link about this error. I checked some of them I did't get answer. above link gives right answer thanks for helping me – kgdc Sep 04 '17 at 13:51

2 Answers2

1

According to gcc reference:

-pthreads

Add support for multithreading using the POSIX threads library. This option sets flags for both the preprocessor and linker. This option does not affect the thread safety of object code produced by the compiler or that of libraries supplied with it.

msc
  • 33,420
  • 29
  • 119
  • 214
-2

It compiles without -pthread just fine

gcc -c thr.c

but it won't link. To make it link, you need -lpthread or -pthread.

gcc thr.c -pthread

Using only the linking flag (-lpthread) should be sufficient (see -pthread, -lpthread and minimal dynamic linktime dependencies ).

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142