我正在尝试学习如何在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