将C程序与标准线程(C11中的<threads.h>)链接的正确方法是什么?

我正在尝试学习如何在C11中使用,因此我尝试编译该示例:

#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);
}

问题在于该程序需要使用额外的链接器标志进行编译:

$ 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

但是我注意到,没有信息可以使用什么标志了,带有-lpthread标志的编译成功了:

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

但这并不意味着它是正确的标志。 我正在使用gcc:

$ gcc --version
gcc (Arch Linux 9.3.0-1) 9.3.0
woamazai 回答:将C程序与标准线程(C11中的<threads.h>)链接的正确方法是什么?

如果您决定在Linux平台上使用,则必须将程序与-lpthread链接。

例如,如果您使用的是GCC,则会找到 join 实现here,并且您还会注意到它只是对pthread_join的调用。

,

请检查以下内容:

如果编译器定义了宏常量 STDC_NO_THREADS (C11),则不提供标题和此处列出的所有名称。

,

为什么使用thread.h?它被认为是劣等的API。使用pthread.h代替POSIX标准。 -lpthread标志在编译期间也用于包括pthread库。 Pthread的手册页: http://man7.org/linux/man-pages/man0/pthread.h.0p.html

本文链接:https://www.f2er.com/2316305.html

大家都在问