我正在努力学习如何在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发布于 2020-05-20 02:32:12
发布于 2020-05-19 21:22:38
请检查这个:
如果编译器定义了宏常量STDC_NO_THREADS(C11),则不提供此处列出的标题和所有名称。
发布于 2020-05-19 21:40:24
为什么要使用线程?它被认为是劣等API。而是使用p线程.h,这是POSIX标准。在编译过程中还使用了-lpthread标志。多线程手册页:http://man7.org/linux/man-pages/man0/pthread.h.0p.html
https://stackoverflow.com/questions/61900881
复制相似问题