VS Code配置C++属性报错:无法找到C++20标准中的barrier头文件
问题描述
VS Code的IntelliSense报以下错误:
cannot open source file "barrier" (dependency of "role_server.h") C/C++(1696)
同时#include <experimental/coroutine>也提示找不到文件。已在c_cpp_properties.json中配置C++20标准,且使用Bazelisk编译代码完全正常,仅VS Code存在该问题,系统为Linux 20.04.1-Ubuntu。当前c_cpp_properties.json配置如下:
{ "configurations": [ { "name": "Linux", "includePath": [ "${workspaceFolder}/**", "/usr/include/**", "/usr/local/include/**", "~/INSTALL/protobuf/src", "${workspaceFolder}" ], "defines": [], "compilerPath": "/usr/bin/g++", "cStandard": "c23", "cppStandard": "c++20", "intelliSenseMode": "linux-gcc-x86", "configurationProvider": "ms-vscode.makefile-tools", "compilerArgs": [ "-std=c++20" ] } ], "version": 4 }
解决方案
1. 检查并升级GCC版本
Ubuntu 20.04默认预装的GCC版本为9.x,而C++20的barrier需要GCC 11及以上版本才完全支持,experimental/coroutine也依赖较高版本的编译器标准库。
- 查看当前GCC版本:
g++ --version - 若版本低于11,通过PPA升级:
sudo add-apt-repository ppa:ubuntu-toolchain-r/test sudo apt update sudo apt install gcc-11 g++-11
2. 更新VS Code的C/C++配置
修改c_cpp_properties.json,指定高版本编译器路径并修正IntelliSense模式:
{ "configurations": [ { "name": "Linux", "includePath": [ "${workspaceFolder}/**", "/usr/include/**", "/usr/local/include/**", "~/INSTALL/protobuf/src", "${workspaceFolder}", // 添加GCC 11的标准库路径 "/usr/include/c++/11", "/usr/include/x86_64-linux-gnu/c++/11" ], "defines": [], "compilerPath": "/usr/bin/g++-11", // 改为g++-11 "cStandard": "c23", "cppStandard": "c++20", "intelliSenseMode": "linux-gcc-x64", // 修正为64位模式 "configurationProvider": "ms-vscode.makefile-tools", "compilerArgs": [ "-std=c++20" ] } ], "version": 4 }
3. 同步Makefile Tools配置
由于配置了configurationProvider: ms-vscode.makefile-tools,需确保该插件也使用正确的编译器和标准。在.vscode/settings.json中添加:
"makefile.configurations": [ { "name": "Linux", "compilerPath": "/usr/bin/g++-11", "cppStandard": "c++20" } ]
4. 重启VS Code生效
按下Ctrl+Shift+P打开命令面板,选择Reload Window,让新配置生效。
原因说明
Bazelisk编译正常是因为它可能使用了项目指定的高版本工具链,而VS Code的IntelliSense依赖本地配置的编译器路径。默认的GCC 9.x不支持C++20的barrier,导致头文件查找失败。
内容的提问来源于stack exchange,提问作者Ethan

