You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Replit中C++线程创建失败,报Undefined reference to `pthread_create`错误

Replit平台C++线程创建失败问题解决

问题情况

在Replit平台编写C++代码创建线程时失败,此前在VS2019等编译器中可正常运行。尝试两种方式均报错:

  1. 使用std::thread时程序无法正常执行
  2. 使用POSIX线程(pthread)时,出现错误:未定义对pthread_create的引用

测试代码示例

使用std::thread的代码

#include <iostream>
#include <thread>
#include <pthread>

void waveThreader()
{
    std::cout << "Hello!";
}

int main()
{
    std::cout << "Start!";
    std::thread thread1(waveThreader);
    thread1.join();
    return 0;
}

使用pthread的代码

#include <iostream>
#include <pthread>

void * waveThreader(void *arguments)
{
    std::cout << "Hello!";
    return NULL;
}

int main()
{
    pthread_t thread1;
    pthread_create(&thread1, NULL, waveThreader, NULL);
    pthread_join(thread1, NULL); // 需等待线程结束避免主线程提前退出
    return 0;
}

(注:原代码存在变量名不一致问题,已修正pthread_create的第一个参数为&thread1,并补充pthread_join)

解决方法

Replit使用GCC编译器,默认不会自动链接pthread库,而Linux环境下C++标准库的std::thread底层依赖pthread,因此需要手动添加链接参数:

  • 打开项目中的.replit配置文件
  • 找到compile字段,修改编译命令,在末尾添加-pthread参数,例如:
    compile = "g++ main.cpp -o main -pthread"
    
  • 重新编译运行代码即可正常创建线程

原理:-pthread参数会告知GCC编译器同时链接pthread库,解决函数引用未定义的问题。

内容的提问来源于stack exchange,提问作者user20342224

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 14:15:40