Chinaunix首页 | 论坛 | 博客
  • 博客访问: 314566
  • 博文数量: 28
  • 博客积分: 2156
  • 博客等级: 大尉
  • 技术积分: 232
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-02 15:31
文章分类

全部博文(28)

文章存档

2011年(7)

2010年(21)

分类: LINUX

2010-07-01 10:46:42

今天开始学习linux下面的多线程编程,根据书上的实例(创建等待线程示例),敲入代码,进行编译,没想到竟然出现这么一个问题,刚开始对于这个问题感觉很困惑,因为我已经添加了这个头文件了,

代码如下:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

void *helloworld(char *argc);

int main(int argc, char *argv[])
{
  int error;
  int *temptr;
  pthread_t thread_id;
  pthread_create(&thread_id, NULL, (void *)*helloworld, "Hello, World!");
  
  if(error = pthread_join(thread_id, (void **)&temptr))
  {
    perror("pthread_join");
    exit(EXIT_FAILURE);
  }
  printf("the id is %d\n", thread_id);
  return 0;
}

void *helloworld(char *argc)
{
  printf("the message is %s\n", argc);
  printf("the main id is %d\n", pthread_self());
  return 0;
}

然后进行编译出现如下错误:

[root@xudonglee AdvanceLinux]# cc thread_create.c
/tmp/ccIcWjHm.o: In function `main':
thread_create.c:(.text+0x31): undefined reference to `pthread_create'

thread_create.c:(.text+0x43): undefined reference to `pthread_join

collect2: ld 返回 1


这个错误跟以前遇到的那个使用头文件时,很多数学函数的找不到的提示类似,那时候是在编译的时候添加“-lm”选项。
而此处产生这个问题原因是:
    pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,和其他一些与线程操作相关的函数时,需要链接该库。

解决方法:
    在编译中要加 -lpthread选项
   

[root@xudonglee AdvanceLinux]# cc thread_create.c -lpthread
[root@xudonglee AdvanceLinux]# ./a.out
the message is Hello,
the main id is -1208116336
the id is -1208116336


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