在 vscode 中配置 c++ 编译与调试环境,核心是让编辑器能调用 mingw 的 gcc 工具链,并通过 launch.json 和 tasks.json 正确驱动编译、链接与 gdb 调试。关键不在于装插件,而在于路径、参数和 json 配置的准确对应。
安装并验证 MinGW-w64(推荐 MSYS2)
直接下载旧版 MinGW 容易出兼容问题,建议用 MSYS2 安装最新 MinGW-w64 工具链:
- 安装后运行
mingw64.exe,执行pacman -Syu && pacman -S mingw-w64-x86_64-toolchain - 将
MSYS2mingw64in添加到系统PATH(重启终端或 VSCode) - 终端中运行
g++ --version和gdb --version确认可用
安装必要插件并设置 C++ 路径
只需两个插件:C/C++(by microsoft) 和 Code Runner(可选,快速运行)。安装后重点配置:
- 按
Ctrl+Shift+P→ 输入C/C++: Edit Configurations (ui) - 在
Compiler path填入完整路径,例如:C:msys64mingw64ing++.exe - 确保
IntelliSense mode设为gcc-x64(匹配你的架构) - 保存后,
c_cpp_properties.json会自动生成,无需手动编辑
配置 tasks.json 实现一键编译
按 Ctrl+Shift+P → Tasks: Configure default Build Task → Create tasks.json file from template → 选 G++ build active file,然后替换为以下内容:
{ "version": "2.0.0", "tasks": [ { "type": "cppbuild", "label": "g++ build active file", "command": "g++", "args": [ "-g", "${file}", "-o", "${fileDirname}${fileBasenameNoExtension}.exe", "-static-libgcc", "-static-libstdc++" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": ["$gcc"], "group": "build", "detail": "compiler: g++" } ] }
说明:-static-libgcc 和 -static-libstdc++ 避免运行时缺 DLL;${file} 表示当前打开的 .cpp 文件,适合单文件项目。
立即学习“C++免费学习笔记(深入)”;
配置 launch.json 启动 GDB 调试
按 Ctrl+Shift+P → Debug: Open launch.json → 选 C++ (GDB/LLDB) → 选 G++ build and debug active file,再修改 program 和 miDebuggerPath:
{ "version": "0.2.0", "configurations": [ { "name": "g++ build and debug active file", "type": "cppdbg", "request": "launch", "program": "${fileDirname}${fileBasenameNoExtension}.exe", "args": [], "stopAtEntry": false, "cwd": "${fileDirname}", "environment": [], "externalConsole": true, "MIMode": "gdb", "miDebuggerPath": "gdb.exe", "setupCommands": [ { "description": "Enable pretty-printing", "text": "-enable-pretty-printing", "ignoreFailures": true } ], "preLaunchTask": "g++ build active file" } ] }
注意:miDebuggerPath 写 "gdb.exe" 即可(前提是已加到 PATH);externalConsole 设为 true 才能输入 cin;preLaunchTask 必须和 tasks.json 中的 label 完全一致。
基本上就这些。改完配置后,打开一个 main.cpp,按 Ctrl+F5 就能自动编译 + 启动调试。不复杂但容易忽略路径和大小写匹配——尤其是 preLaunchTask 名字拼错会导致“无法找到构建任务”。