首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将C程序与标准线程(从<threads.h>到C11)连接的正确方法是什么?

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

Stack Overflow用户
提问于 2020-05-19 21:14:38
回答 3查看 1.1K关注 0票数 2

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

代码语言:javascript
复制
#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);
}

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

代码语言:javascript
复制
$ 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标志的编译是成功的:

代码语言:javascript
复制
$ gcc --std=c17 main.c -lpthread && ./a.out 
Hello world of C11 threads from thread 140377624237824.
Thread 140377624237824 returned 0 at the end

但这并不意味着它是正确的旗帜。我在用gcc:

代码语言:javascript
复制
$ gcc --version
gcc (Arch Linux 9.3.0-1) 9.3.0
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-05-20 02:32:12

如果您决定在Linux平台上使用< threads.h>,则必须将您的程序与-lpthread链接起来。

例如,如果您使用GCC,您将发现join实现这里,并且您还会注意到它只是对加入的调用。

票数 3
EN

Stack Overflow用户

发布于 2020-05-19 21:22:38

请检查这个:

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

票数 1
EN

Stack Overflow用户

发布于 2020-05-19 21:40:24

为什么要使用线程?它被认为是劣等API。而是使用p线程.h,这是POSIX标准。在编译过程中还使用了-lpthread标志。多线程手册页:http://man7.org/linux/man-pages/man0/pthread.h.0p.html

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61900881

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档