VS Code在ubuntu中执行多线程程序时报错:undefined reference to `pthread_create‘

在Ubuntu环境下使用VSCode进行C++多线程编程时遇到编译错误,提示未定义引用'pthread_create'。问题源于缺少对pthread库的链接。解决方法是在VSCode的任务配置文件tasks.json中添加'-lpthread'参数,确保在编译时链接pthread库。通过修改tasks.json,用户现在可以顺利地使用Ctrl+F5运行多线程程序。

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

VS Code在ubuntu中执行多线程程序时报错:

问题描述:

最近在学习C++并发多线程,在ubuntu中使用VS Code编写多线程代码后,Ctrl+F5运行程序,结果出现了以下的问题:

#include<iostream>
#include<vector>
#include<thread>
using namespace std;
//一个单独的main函数,运行实际上是主线程在执行,主线程从main返回,则整个进程执行完毕

//自己创建的线程需要从一个函数开始运行
void MyPrint(){
    cout<<"我的线程开始"<<endl;
    ////////
    cout<<"我的线程结束了"<<endl;
}

int main(){
    //此时这个代码中有两个线程在同时在执行,同时执行两个任务
    thread mytobj(MyPrint);
    mytobj.join();
    cout<<"I love china"<<endl;
    return 0;
}

在这里插入图片描述

> Executing task: C/C++: g++ 生成活动文件 <

正在启动生成...
/usr/bin/g++ -g /home/liukai/文档/Code_WorkSpace/CPP_CONCURRENCY/project.cpp -o /home/liukai/文档/Code_WorkSpace/CPP_CONCURRENCY/project
/usr/bin/ld: /tmp/ccb0x5iT.o: in function `std::thread::thread<void (&)(), , void>(void (&)())':
/usr/include/c++/9/thread:126: undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status

生成已完成,但出现错误.
The terminal process terminated with exit code: -1.

Terminal will be reused by tasks, press any key to close it.

重点在于:

/usr/include/c++/9/thread:126: undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status

原因分析:

百度之后,发现是 在ubuntu平台下调用pthread_create()函数,用gcc编译时出现Undefined reference to 'pthread_create’的问题。是因为pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,需要链接该库。

解决方案:

知道原因后问题就很好解决了,只需在每次编译时用gcc的-l选项将pthread库链接一下就行了。
在这里插入图片描述
但是能不能在VS Code里使其链接到这个静态库,然后直接Ctrl+F5直接运行,当然可以。
在VS Code的搜索框输入tasks.json,修改tasks.json文件。
在这里插入图片描述

把"args"修改为如下,在最后像命令行中一样加上“-lpthread”,保存后即可ctrl+F5运行多线程程序:

            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}",
                "-lpthread"
            ],

在这里插入图片描述


评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值