解决Ubuntu gcc编译线程创建函数pthread_create()出现 undefined reference to `pthread_create'的错误

本文详细解析了在Linux环境下使用gcc编译多线程程序时遇到的undefined reference to `pthread_create`错误。主要原因是编译时未正确链接pthread库。文章提供了具体的解决步骤,包括如何在gcc命令中添加正确的参数以链接到pthread库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

undefined reference to `pthread_create'错误

问题描述

在使用linux编译创建多线程时会出现undefined reference to `pthread_create’错误

命令行编译错误结果如下

jill@DESKTOP-EIC0724:~$ gcc -pthread pthread_create.c
/tmp/cc3e3bXk.o: In function `main':
pthread_creat.c:(.text+0x90): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status

问题原因及解决

首先看一下男人:

jill@DESKTOP-EIC0724:~$ man pthread_create

NAME
       pthread_create - create a new thread
SYNOPSIS
       #include <pthread.h>
       int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);
       Compile and link with -pthread.
  在最后一句Compile and link with -pthread意思是编译需要附加-pthread

也就是说pthread不是Linux下的默认的库,在链接的时候,无法找到phread库中函数的入口地址,于是链接会失败。所以在gcc编译的时候,附加要加 -lpthread 参数即可解决。
注意: ubuntu必须把-pthread放在后面
我在连接的时候首先就把-pthread加上,但是还是出现这种错误,而其他非Ubuntu的Linux发行版不会出现此类错误,具体做法参考如下.

jill@DESKTOP-EIC0724:~$ gcc pthread_create.c -o pthread_create -pthread
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值