C 语言学习之:问题解决之—多线程编程代码运行时报错:undefined reference to pthread_create;undefined reference to pthread_join

问题描述

  • 选了一计算机系统的课,课程要求在 linux 系统上运行一些 C 的代码,学到多线程的地方,在 linux 上安装了一个集成开发环境:Jetbrain 公司的 Clion,但是编译线程程序的时候无论如何也无法编译成功,报的错误:

[2/2] Linking C executable untitled1
FAILED: untitled1
: && /usr/bin/cc -g CMakeFiles/untitled1.dir/main.c.o CMakeFiles/untitled1.dir/test2.c.o -o untitled1 && :
CMakeFiles/untitled1.dir/test2.c.o: In function main': /tmp/guest-6kn2dp/CLionProjects/untitled1/test2.c:21: undefined reference topthread_create’
/tmp/guest-6kn2dp/CLionProjects/untitled1/test2.c:25: undefined reference to pthread_create' /tmp/guest-6kn2dp/CLionProjects/untitled1/test2.c:29: undefined reference topthread_join’
/tmp/guest-6kn2dp/CLionProjects/untitled1/test2.c:33: undefined reference to `pthread_join’
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.

问题原因

  • 因为通过编译器没有链接到线程库。所以我们通过下列的两种方法来进行手动链接:

问题解决方案1

  • 使用命令行来显式地链接线程库 -l pthread 或者 -pthread 来编译文件:
gcc test2.c -o test2 -lpthread
  • 运行文件:
./test2    //注意这里没有扩展名
  • 如果想编译运行一条龙,使用下面命令:
gcc test2.c -o test2 -lpthread && ./test2

方案2:修改 Clion 中的 CmakeLists.txt 文件

  • 在 cmakelists.txt 文件末尾加这两行,
  • 一定要注意,target_link_library 中要指定自己的工程名称哦!
find_package(Threads REQUIRED)
target_link_libraries(untitled Threads::Threads)

在这里插入图片描述

  • 改完名称之后,需要将 cmakelists.txt 文件重新 reload 一下,reload 的按钮在 cmakelists.txt 页面的右上方。

一个粗心的提醒:
别忘了把其他文件里有主函数 main 的代码注释掉哦~否则会报下面的错误:
在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

暖仔会飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值