0%

vscode使用指定C++版本编译程序

前情提要

前段时间刷LeetCode的时候需要本地调试,使用了下面这个方法初始化vector

1
std::vector<int> list = {1,4,3,7,4,5};

但是编译的时候一直提示Error: non-aggregate type 'vector<int>' cannot be initialized with an initializer list

vscode默认编译命令是直接运行g++

1
2
3
4
5
6
7
"code-runner.executorMap": {

"javascript": "node",
"java": "cd $dir && javac $fileName && java $fileNameWithoutExt",
"c": "cd $dir && gcc $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
"zig": "zig run",
"cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",

而默认的g++支持的C++版本比较老旧,可以用命令检查g++支持的默认c++版本
g++ -dM -E -x c++ /dev/null | grep -F __cplusplus
如下输出

1
2
magicdian@MacBook-Pro-14 ~ % g++ -dM -E -x c++  /dev/null | grep -F __cplusplus
#define __cplusplus 199711L

而我使用的初始化方法是c++11时引入的,因此我需要使用命令g++ -std=c++11 命令编译

修改为(g++后面添加 -std=c++11)

修改过程

1. 打开vscode设置

mac端快捷键 :Command + ,

2. 在设置中搜索executorMap

如图所示

3. 在g++命令后面添加 -std=c++11

1
2
3
4
5
6
7
"code-runner.executorMap": {

"javascript": "node",
"java": "cd $dir && javac $fileName && java $fileNameWithoutExt",
"c": "cd $dir && gcc $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
"zig": "zig run",
"cpp": "cd $dir && g++ -std=c++11 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",

像上面这样,也可以参考下面的截图