因为打算刷题,嫌弃codeblocks
界面太丑了。vs界面经过我更换之后倒是看着很舒服,但是用vs刷题实在是大材小用,毕竟oj
都只是单文件(而且打开vs也挺慢的(卡顿感))。所以果断投入vscode
的怀抱了。
一开始是按照热门博客整理:Visual Studio Code (vscode) 配置C、C++环境/编写运行C、C++(主要Windows、简要Linux)_一苇以航-优快云博客_vscode配置c++环境这个来配置的,结果出现prelaunchtask"g++"已终止, 退出代码为1解决
的问题。所以我还是老老实实看着官网文档配置环境吧~
这篇博客就是想记录一下,避免大多数坑,使得小白也能使用vscode
运行C++程序。本文所用系统为Windows系统。
安装编译,调试环境
首先需要下载Mingw-w64
,我们可以通过MSYS2
下载。点击MSYS2下载MSYS2安装包。然后按照MSYS2通过msys2下载Mingw-w64
。
下载完成后通过以下步骤将MinGW bin所在文件加入系统环境变量中:
-
按下win + s快捷键,在搜索框中搜索编辑系统环境变量。
-
点击环境变量,然后在系统变量中选中Path,点击编辑然后点击新建即可。
最后,我们可以打开终端检查一下环境是否配置完成,输入以下命令:
g++ --version
gdb --version
生成.vscode文件
在工作区中,生成一个.vsode
文件夹,该文件夹包含三个文件:
tasks.json
(build instructions)launch.json
(debugger settings)c_cpp_properties.json
(compiler path and IntelliSense settings)
如图:
生成tasks.json文件
在最上面一行选择Terminal > Configure Default Build Task,然后在弹出的选项中选择g++.exe 生成活动文件,自动生成tasks.json
文件
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++.exe 生成活动文件",
"command": "D:\\MSYS2\\msys64\\mingw64\\bin\\g++.exe",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "编译器: D:\\MSYS2\\msys64\\mingw64\\bin\\g++.exe"
}
]
}
生成launch.json文件
在最上面一行选择Run > Add Configuration,然后选择C++(GDB/LLDB),然后选择g++.exe build and debug active file
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "g++.exe - 生成和调试活动文件",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"miDebuggerPath": "D:\\MSYS2\\msys64\\mingw64\\bin\\gdb.exe",
"setupCommands": [
{
"description": "为 gdb 启用整齐打印",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: g++.exe 生成活动文件"
}
]
}
生成c_cpp_properties.json文件
按下Ctrl+Shift+P
选择C/C__:Edit Configurations(JSON)即可生成c_cpp_properties.json
文件。
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"windowsSdkVersion": "10.0.19041.0",
"compilerPath": "D:\\Visual Studio\\Microsoft Visual Studio\\2022\\Community\\VC\\Tools\\MSVC\\14.30.30705\\bin\\Hostx64\\x64\\cl.exe",
"cStandard": "c17",
"cppStandard": "c++17",
"intelliSenseMode": "windows-msvc-x64"
}
],
"version": 4
}
编译运行
写好代码之后,按Ctrl + F5运行程序,会发现有一个黑框一闪而过,这是正常现象,只需在return 0;
的上一句加上getchar();
即可
后序
我在配置环境的过程中,还遇到了vs code中命名空间不明确
问题,如果大家也有遇到这个问题,可以参考一下解决vs code中命名空间不明确问题_爱打羽球的码猿的博客-优快云博客这篇博客。