您的位置:首页 > Web前端

UNIX环境高级编程中的11章程序11-2编译问题---undefined reference to `pthread_create'

2015-03-10 21:37 591 查看
#include<apue.h>
#include<pthread.h>

pthread_t ntid;
void
printids(const char *s)
{
pid_t pid;
pthread_t tid;

pid=getpid();
tid=pthread_self();
printf("%s pid %lu tid %lu (0x%lx)\n",s,(unsigned long)pid,(unsigned long)tid,(unsigned long)tid);
}

void *
thr_fn(void *arg)
{
printids("new thread: ");
return((void *)0);
}

int
main(void)
{
int err;

err=pthread_create(&ntid,NULL,thr_fn,NULL);
if(err!=0)
err_exit(err,"can't create thread");
printids("main thread:");
sleep(1);
exit(0);
}


编译这段代码时出现上述问题原因:

pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,需要链接该库。

解决方法:在编译中要加 -lpthread选项,类似于在使用<math.h>是的选项 -lm.

编译:gcc -o program11-2 program11-2.c -lapue -lpthread
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐