与clang++一起使用的VS代码在构建良好的C++文件中显示错误

VS Code, used with clang++, shows errors in a C++ file that builds fine

本文关键字:C++ 文件 错误 显示 构建 一起 clang++ 代码 VS      更新时间:2023-10-16

这个问题已经解决。我删除了c_cpp_properties.json,并允许Vs Code通过运行命令c/c++ configuration (JSON)重新生成它


我正在尝试设置Vscode以与C++文件一起使用,遵循此处的指示:

https://code.visualstudio.com/docs/cpp/config-clang-mac

文件构建并运行良好

问题是,我在文件中的两个位置都出现了错误(红色的歪歪扭扭)。其中一个说"预期;"(与声明的vector<string>一致),另一个说类似于"基于范围的循环是C++11扩展">

他们提供的样本文件是

#include <vector>
#include <string>
using namespace std;
int main() 
{
vector<string> msg{"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"};

for (const string& word : msg)
{
cout << word << " ";
}
cout << endl;
}

我使用的tasks.json是

{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "clang++ build active file",
"command": "/usr/bin/clang++",
"args": [
"-std=c++17",
"-stdlib=libc++",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

c_cpp_properties.json表示:

{
"configurations": [
{
"name": "Mac",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [],
"macFrameworkPath": [
"/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks"
],
"compilerPath": "/usr/bin/clang",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "clang-x64"
}
],
"version": 4
}

我解决了这个问题。我不确定具体是哪一步解决了这个问题,但我可以在这里为将来遇到这个问题的人提供一些有用的信息。

首先,要注意您启用了哪些C++扩展。首先坚持使用Microsoft C/C++扩展(主扩展)。

其次,确保已启用扩展。似乎有一种方法可以在不启用扩展的情况下安装它们。

第三,VS Code会在您将某些json文件销毁后重新生成它们。例如,我删除了c_cpp_properties.json文件,然后从命令面板运行"C/C++编辑配置(JSON)",文件又回来了,可能解决了我遇到的任何问题。