【问题标题】:VSCode and C++: Slightly lost with this errorVSCode 和 C++:因此错误而略显迷失
【发布时间】:2022-01-20 15:17:27
【问题描述】:

我使用示例 helloworld 程序并得到对我来说毫无意义的语法错误。奇怪的是程序运行得很好,但是代码中的红色曲线让我很困扰,我想知道为什么会这样。

代码

#include <iostream>
#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 文件

{
    "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
            }
        }
    ]
}

带下划线的错误之一是 msg 和括号之间的空格:

no instance of constructor "std::__1::vector<_Tp, _Allocator>::vector [with _Tp=std::__1::string, _Allocator=std::__1::allocator<std::__1::string>]" matches the argument list -- argument types are: (const char [6], const char [4], const char [6], const char [5], const char [8], const char [23])

下一个在for循环的冒号处:

reference variable "word" requires an initializer

最后一个是for循环的右括号(在msg之后):

expected an expression

是什么导致了这些错误,程序如何仍在运行? (我应该提一下,我对 C++ 不是很熟悉,但很高兴知道这些原因以及我是否应该关注它们)

【问题讨论】:

  • "-stdlib=libc++" 在 Mac 上是完全没有必要的。它默认使用 LLVM 套件。仅安装 C/C++ 扩展是不够的。您必须对其进行配置。
  • 我想你的 c_cpp_properies.json 设置不正确

标签: c++ visual-studio-code c++17


【解决方案1】:

您是否配置了您的 c++ VS Code 扩展?

例如:

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

重要的位是:“cStandard”:“c11”, "cppStandard": "c++17"

【讨论】:

  • 这修复了它! cStandard 设置为 c11,cppStandard 设置为 c++98 - 现在已删除错误。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多