用标准线程链接C程序的正确方法是什么( 来自C11)?

问题描述 投票:0回答:3

我正在尝试学习如何在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
c multithreading linker pthreads c11
3个回答
0
投票

请检查此:


0
投票

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.