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

gcc 9.4.0/Clang 10编译std::jthread失败,如何解决?

问题:std::jthread编译报错解决方法

环境信息

  • GCC版本:gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1)
  • Clang版本:clang version 10.0.0-4ubuntu1,目标架构x86_64-pc-linux-gnu,线程模型posix

问题代码

#include <thread>
#include <vector>

int main(){
  std::vector<std::jthread> myJThreads; 
  return 0;
}

尝试过的编译命令

g++ -O2 -std=c++2a -Wall -Wextra -Wpedantic  -lm -lstdc++ example.cpp -pthread -o example
clang -O2 -std=c++2a -Wall -Wextra -Wpedantic  -lm -lstdc++ example.cpp -pthread -o example
clang++-12 -O2 -std=c++2a -Wall -Wextra -Wpedantic  -lm -lstdc++ example.cpp -pthread -o example

报错信息

error: ‘jthread’ is not a member of ‘std’;
error: no member named 'jthread' in namespace 'std'

解决方法

std::jthread是C++20标准新增的特性,你的编译器版本对该特性的支持存在缺失:

  1. GCC 9.4.0仅实现了部分C++20特性,std::jthread是在GCC 10版本才正式纳入标准库的,所以GCC 9.x无法识别这个类型。
  2. Clang 10.0.0不支持std::jthread,该特性从Clang 11开始才被支持;你尝试的clang++-12本身具备支持能力,但编译参数需要调整:
    • 需明确指定-std=c++20而非-std=c++2a(c++2a是C++20制定过程中的临时标识,部分旧版本编译器对正式的c++20参数支持更准确)
    • 无需手动添加-lstdc++,clang++会自动链接标准库,手动添加可能引发版本冲突

针对你的Ubuntu 20.04环境,推荐以下两种解决方式:

方式一:升级GCC到10及以上版本

通过Ubuntu官方工具链PPA安装:

sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt update
sudo apt install gcc-10 g++-10

编译时使用升级后的编译器:

g++-10 -O2 -std=c++20 -Wall -Wextra -Wpedantic example.cpp -pthread -o example

方式二:修正clang++-12的编译参数

直接使用正确的编译命令:

clang++-12 -O2 -std=c++20 -Wall -Wextra -Wpedantic example.cpp -pthread -o example

替代方案(不升级编译器)

如果无法升级编译器,可以将std::jthread替换为std::thread,手动管理线程生命周期,比如在容器销毁前调用join()等待线程结束:

#include <thread>
#include <vector>

int main(){
  std::vector<std::thread> myThreads;
  // 添加线程后需手动join
  for(auto& t : myThreads) {
    if(t.joinable()) t.join();
  }
  return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:45:54