前面介绍了基于Visual Studio Code 构建C/C++ IDE(Mac OS), 设置完成后即可用来开发C++程序。但是默认使用的是c++98,当使用c++11中的特性,如vector 等时则编译或者预检查都会报错。下面介绍如何进行解决。

测试代码

#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char *argv[]) {
  vector<int> heap = {9, 8, 7, 6, 5, 4, 3, 2, 1};
  for (vector<int>::iterator it = heap.begin(); it != heap.end(); it++) {
    cout << (*it) << endl;
  }
  return 0;
}

编译报错

报错信息:

/Users/dongguangqing/Documents/SublimeDoc/heap.cpp:36:15: error: non-aggregate type 'vector<int>' cannot be initialized with an initializer list
  vector<int> heap = {9, 8, 7, 6, 5, 4, 3, 2, 1};

原因: 报这个错误是因为c++ 98中不允许在初始化vector容器时指定初始化元素值。 解决办法: 在.vscode/task.json 中配置c++11支持,加上-std=c++11,-stdlib=libc++配置,如:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "g++ build cpp program",
            "type": "shell",
            "command": "g++",
            "args": [
                "-g",
                "-std=c++11",
                "-stdlib=libc++",
                "-o",
                "${fileBasenameNoExtension}",
                "${file}"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

静态检查报错

报错信息: “non-aggregate type 'vector' cannot be initialized with an initializer list” 如:

报错原因:这个是因为C/C++ Clang Command Adapter 这个插件没有配置默认支持C++11. 解决办法:点击Code->Preferences->Settings, 搜索Clang: Cflags、Clang: Cxxflags增加C++11 的配置即可

  • Clang: Cflags增加Item: "-std=c11"
  • Clang: Cxxflags增加Item: "-std=c++11"