1、前期工作
安装vscode,vscode官网
安装mingw64并配置其g++的bin目录到系统环境变量
打开vscode:
安装如下插件:
- c++ extension(语言相关)
- code runner (自动编译运行工具)
配置步骤:
1、在自己工程(文件夹)目录下新建一个hello.cpp,测试内容:
#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;
}
2、新建.vscode文件夹,里面新建settings.json文件,内容如下:
下面只需要你修改"C_Cpp.default.includePath"
为你相应的库目录即可,你可以只换E:\\Program Files
部分保证对应即可
{
"editor.fontSize": 25,
"window.zoomLevel": -1,
"code-runner":{
"runInTerminal": true, //在集成终端展示运行
"clearPreviousOutput": true, //运行前清楚之前输出
"saveAllFilesBeforeRun": false,//运行前即时保存所有文件
"saveFileBeforeRun": true,//运行前即时保存
"executorMap":{
"cpp": "g++ $fileName -o $fileNameWithoutExt -W -Wall -O2 -std=c++17 && ./$fileNameWithoutExt",
"c": "gcc $fileName -o $fileNameWithoutExt -W -Wall -O2 -std=c17; ./$fileNameWithoutExt",
},
},
//cpp代码静态代码检查标准
"C_Cpp.default.cppStandard": "c++17",
"C_Cpp.default.cStandard": "c17",
//头文件包含路径,配置了环境变量也可以不设
"C_Cpp.default.includePath": [
"E:\\Program Files\\mingw64\\lib\\gcc\\x86_64-w64-mingw32\\8.1.0\\include\\**",
"E:\\Program Files\\mingw64\\x86_64-w64-mingw32\\include"
],
"files.associations": {
"iostream": "cpp"
},
//编译路径设置了环境变量就自动识别可以不用设置
// "C_Cpp.default.compilerPath": "E:\\Program Files\\mingw64\\bin\\g++",
}
ctrl+alt+n运行选中程序。(你也可以进入设置修改code runner运行快捷键为ctrl+R)
结束
你还可以安装一些插件:
- Bracket Pair Colorizer 2
- vscode-icons
各有什么用自己看简介
如果你对编译环境不是那么执着,能够运行自己的代码到这里就够了。
如果你还想折腾一下自己,想试试微软的高级无缘无故服务(当然你幸运也可能不会遇到),在.vscode文件夹下添加tasks.json和launch.json文件内容分别是:
tasks.json:
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "g++ compile",
"command": "E:\\Program Files\\mingw64\\bin\\g++.exe",
"args": [
"-g",
"${file}",
"-o",
"-W", "-Wall", "-O2",
"-std=c++17",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": ["$gcc"],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
launch,json:
{
"version": "0.2.0",
"configurations": [
{
"name": "gdb Nobug",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "gdb", // 调试程序gdb位置,加了环境变量不用
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: g++.exe build active file" //前置编译程序与tasks相连
}
]
}
然后f5调试即可
如果你遇到了奇奇怪怪的问题,多查询一下。如果半天没解决,试一试ctrl+s保存文件, 重启vscode,关机重启,看看自己的项目路径是否有中文名等说不定就好了。
注意注意:
官方在tasks.json文件中将label设置为"C/C++: g++.exe build active file",这里运行你可能会遇到g++.exe: fatal error: no input files
等错误,经过本人车机环境测试,不是斜杠,冒号,++的锅,关键凑在一起就有这个错误,可能是因为和launch里面的重名了建议换一个好听的名字,比如在任务配置里改为Big Son Microsoft
也能运行。这里有同学知道原因也麻烦告知大伟一下。
最后祝你一次配置成功!