C中Pthread函数的未定义参考

时间:2012-12-04 15:43:01

标签: c unix pthreads undefined-reference

  

可能重复:
  undefined reference to pthread_create in linux (c programming)

我正在尝试在C中的Ubuntu中实现Thread链。当我编译下面的代码时,即使我添加了头文件,我也会得到Undefined引用这些线程库函数的错误。我也得到了分段错误错误。这是为什么?我没有在程序中的任何地方访问一些未初始化的内存。这是代码:

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

void* CreateChain(int*);

 int main()
{
int num;

pthread_t tid;


scanf("Enter the number of threads to create\n %d",&num);

pthread_create(&tid,NULL,CreateChain,&num);

pthread_join(tid,NULL);

printf("Thread No. %d is terminated\n",num);

return 0;
}

void* CreateChain(int* num )
 {
pthread_t tid;

if(num>0)
{
    pthread(&tid,NULL,CreateChain,num);
    pthread_join(tid,NULL);

    printf("Thread No. %d is terminated\n",*num);
}
else
    return NULL; 

return NULL;
}

我收到以下警告,并且出于某种原因没有出现Scanf提示。

enter image description here

此致

3 个答案:

答案 0 :(得分:2)

pthread.h头文件提供了pthread函数的前向声明。这告诉编译器这些函数存在并具有一定的签名。但是,它不会告诉链接器有关在运行时何处找到这些函数的信息。

要允许链接器解析这些调用(决定跳转到代码内部或不同的共享对象中),需要通过添加

来链接相应的(pthread)库。
-pthread

到你的构建命令行。

[请注意,也可以使用-lpthreadThis previous question表示为什么-pthread更可取。]

代码还有其他各种问题值得关注

  • scanf行应分为printf("Enter number of threads\n");scanf("%d", &num);以显示用户提示
  • CreateChain的签名是错误的 - 它应该采用void*参数。您总是可以在函数内部执行int num = *(int*)arg;之类的操作来检索线程数。
  • CreateChain内的逻辑看起来不对。您当前将指针与0进行比较 - 我认为您的意思是比较线程数而不是?此外,如果你没有减少在某处创建线程的数量,你最终会得到永远创建线程的代码(或者直到你用完句柄,这取决于不同线程的调度方式)。

答案 1 :(得分:1)

尝试编译如下:

gcc -Wall -pthread test.c -o test.out

-pthread是一个明确告诉链接器解析与<pthread.h>

相关的符号的选项

答案 2 :(得分:0)

添加-lpthread

gcc -o test test.c -lpthread
相关问题