【发布时间】:2023-03-14 20:32:01
【问题描述】:
我尝试编译一个包含线程的 c 文件。但我试图像这样编译正常的方式
gcc -o thread thread.c -Wall
但它给出了一个错误。但我试图这样编译
gcc -pthread -o 线程 thread.c -Wall
成功了。这是什么原因和 -pthread 标志会做什么? 下面是我的 C 代码
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
void *thread_function(void *arg)
{
int a;
for(a=0;a<10; a++)
{
printf("Thread says hi!\n");
sleep(2);
}
return NULL;
}
int main(void)
{
pthread_t mythread;
if ( pthread_create( &mythread, NULL, thread_function, NULL) )
{
printf("error creating thread.");
abort();
}
if ( pthread_join ( mythread, NULL ) )
{
printf("error joining thread.");
abort();
}
printf("Main thread says hi!\n");
exit(0);
}
【问题讨论】:
-
你应该看看:stackoverflow.com/questions/23250863/…。本质上,您需要告诉编译器在 pthread 库中链接
-
gcc 文档有什么特别不清楚的地方?
-
其实 -pthread 和 -lpthread 都是平台相关的。一些标准 C 库,例如 Android Bionic,提供了
pthread_create()等的内部实现。如果我没有帮助,请阻止我;) -
我没有看到这些链接。有很多关于这个错误的链接。我检查了其中一些我没有得到答案。上面的链接给出了正确的答案谢谢你帮助我
标签: c multithreading gcc