最近买了本C++20的书,想要自己配置下在VScode的环境
例子代码:
#include <iostream>
#include <format>
int main()
{
std::cout << std::format("Hello, world! {0}", 123) << std::endl;
// 输出:Hello, world! 123
std::string str = std::format("The answer is {0}", 42);
// str 的值为 "The answer is 42"
int a = 1, b = 2;
std::cout << std::format("a = {0}, b = {1}", a, b) << std::endl;
// 输出:a = 1, b = 2
}
以下是详细步骤:
1.首先下vscode的C++插件

输入了代码但不能直接编译运行代码,所以我们还需要下载最新版的C++20 MinGW。
2、去官网下载gcc最新版本
官网的地址
点击下面的Downloads

点击进入Downloads页面后找到这个超链接MingW,再次点击

点击这里的GitHub按钮

跳转到Github网站页面中,页面是这个样子(本文写的日期是2023年11月24日,页面可能不符合,选择最新版本下载就好)

找到这个下载

如果下载失败或者无法上GitHub的,可以使用我的链接分享,也能支持C++20
链接:https://pan.baidu.com/s/1E5M-olqoC5d0w465rWYgyA?pwd=qxc2
提取码:qxc2
下载完成后就去文件夹中解压,解压后大概是这个样子

设置计算机中的环境变量,在path中添加bin的路径,我自己是安装在C盘下,如果你们下载在其他盘中,选择成自己的路径,不需要一定C盘

在cmd命令提示符窗口中输入gcc -v查看版本

出现这些内容就说明你gcc配置环境变量好了
3.去配置VSCode文件
来到VS Code,去修改cpp的配置文件,去 c_cpp_properties.json 文件里,在"includePath"下加入4条头文件路径,然后把"compilerPath"改掉,"cppStandard"直接换成c++20或c++23 。
这里的运行就算编译失败也无所谓,先编译生成.vscode文件夹

你cpp文件夹中.vscode文件夹中


我的c_cpp_properties.json
{
"configurations": [
{
"name": "Win32",
"includePath": [
"C:\\Program Files\\mingw64\\include",
"C:\\Program Files\\mingw64\\x86_64-w64-mingw32\\include",
"C:\\Program Files\\mingw64\\lib\\gcc\\x86_64-w64-mingw32\\12.2.0\\include",
"C:\\Program Files\\mingw64\\lib\\gcc\\x86_64-w64-mingw32\\12.2.0\\include\\c++",
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"compilerPath": "C:\\Program Files\\mingw64\\bin\\g++.exe",
"cStandard": "c17",
"cppStandard": "c++23",
"intelliSenseMode": "windows-gcc-x64"
}
],
"version": 4
}
然后进入到 tasks.json ,对args、command和label做一些修改,command也可以直接写g++;args里一定要写"-std=c++2a"或者"-std=c++23"。
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++.exe 生成活动文件",
"command": "C:\\Program Files\\mingw64\\bin\\g++.exe",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-std=c++23",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "调试器生成的任务。"
}
],
"version": "2.0.0"
}
重新启动一下vscode,然后编译应该能运行了

输出结果

4.配置code Runner,以支持C++20

首先去插件中下载coderunner,下载后重启vscode,然后右键点击codeRunner进去插件的扩展设置中

设置默认编程语言C++

然后找到Executor Map,点 "在 settings.json 中编辑",

在cpp那一行g++后面加上 -std=c++2a(这里不能支持23),保存然后返回代码 。
我的那行代码
"cpp": "cd $dir && g++ -std=c++2a $fileName -o $fileNameWithoutExt && dirfileNameWithoutExt",

现在重启vscode后再次返回cpp代码中,右键Run Code,现在就能直接编译运行了


现在就完成了VSCode对于C++20的配置,希望能帮助到大家。