Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1705302
  • 博文数量: 263
  • 博客积分: 1218
  • 博客等级: 少尉
  • 技术积分: 2862
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-19 02:33
文章分类

全部博文(263)

文章存档

2020年(12)

2019年(2)

2018年(10)

2016年(1)

2015年(20)

2014年(115)

2013年(46)

2012年(37)

2011年(20)

分类: C/C++

2011-08-24 21:41:09

pthread_create函数编译时报错:undefined reference to 'pthread_create'
#include
#include
#include
#include/*for exit()*/
void *fun1(void *a)
{
        /*在创建的线程中输出线程号*/
        printf("the thread created ID is %d",pthread_self());
        return (void *)0;
}
void *fun2(void * a)
{
        printf("the thread created ID  is %d",pthread_self());
        pthread_exit((void *)1);
}
int main()
{
        pthread_t tid1,tid2;
        void * rval_ptr1,*rval_ptrl2;
        tid1=pthread_create(&tid1,NULL,fun1,NULL);
        if(tid1!=0)
                {
                perror("pthread creat error:");
                exit(1);
                }
        /* else主线程等待线程1终止*/
        pthread_join(tid1,&rval_ptr1);
        printf("the return of  pthread ID %d is %d",tid1,rval_ptr1);

        tid2=pthread_create(&tid2,NULL,fun2,NULL);
        /*等待线程2终止*/
        pthread_join(tid2,&rval_ptr2);
        printf("the return of pthread ID  %d is %d",tid2,rval_ptr2);
        return 0;
}

由于pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数时,在编译中要加 -lpthread参数。

例如:在加了头文件#include 之后执行 pthread.c文件,需要使用如下命令:

    gcc thread.c -o thread -lpthread

这种情况类似于的使用,需在编译时加 -m 参数。

接着编译就过了,可是运行时却提示说段错误,个人觉得应该是指针出问题吧,可是都给指针进行malloc后还是同样的错误,在网上找了一下原来是pthread_create出问题 。

要这样编译:  #  gcc -o pthread pthread.c  static /usr/lib/libpthread.a

来自:

http://hi.baidu.com/bobo712/blog/item/6b29c11157d76fc1a6ef3f50.html

阅读(4183) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~