What is proper way of linking C program with standard threads (<threads.h> from C11)?

Viewed 1003

I'm trying to learn how to use in C11, so I've tried to compile that example:

#include <stdio.h>
#include <threads.h>

int run(void *arg)
{
    printf("Hello world of C11 threads from thread %lu.\n", thrd_current());
    fflush(stdout);
    return 0;
}

int main()
{
    thrd_t thread;
    if (thrd_success != thrd_create(&thread, run, NULL))
    {
        perror("Error creating thread!");
        return 1;
    }

    int result;
    thrd_join(thread, &result);
    printf("Thread %lu returned %d at the end\n", thread, result);
    fflush(stdout);
}

The problem is that the program needs to be compiled with extra linker flags:

$ gcc --std=c17 main.c
/usr/bin/ld: /tmp/ccEtxJ6l.o: in function `main':
main.c:(.text+0x66): undefined reference to `thrd_create'
/usr/bin/ld: main.c:(.text+0x90): undefined reference to `thrd_join'
collect2: error: ld returned 1 exit status

But nowhere is information what flags should I use, I've noticed, that compilation with -lpthread flag is succesfull:

$ gcc --std=c17 main.c -lpthread && ./a.out 
Hello world of C11 threads from thread 140377624237824.
Thread 140377624237824 returned 0 at the end

But it does not mean that it is right flag. I'm using gcc:

$ gcc --version
gcc (Arch Linux 9.3.0-1) 9.3.0
3 Answers

If you have decided to use < threads.h> on the Linux platform, you must link your program with -lpthread.

for example, if you are using GCC you will find the join implementation here and you will also notice that it is just a call to pthread_join.

Please check this:

If the macro constant STDC_NO_THREADS(C11) is defined by the compiler, the header and all of the names listed here are not provided.

Related