VS Code 需手动配置编译器、tasks.json 和 launch.json 才能运行调试 C++ 项目;必须先安装 g++/MinGW/clang++ 并验证版本,再安装 C/C++ 与 CMake Tools 等扩展,确保 tasks.json 含 -g 参数、launch.json 中 preLaunchTask 与 task label 一致。
VS Code 本身不是 C++ IDE,它需要手动配置编译器、构建工具和调试器才能真正跑起来 C++ 项目。没配对 tasks.json、launch.json 或漏装 g++ / clang++,写完 main.cpp 点运行只会报错“终端中找不到 g++”或“无法启动调试会话”。
VS Code 不自带编译器,必须先在系统层面装好 g++(Linux/macOS)或 MinGW-w64(Windows),否则后续所有配置都无效。
Studio Installer 后就以为“有编译器了”——VS Code 默认不识别 MSVC 的 cl.exe,除非你额外配 vcvarsall.bat 环境,建议新手直接用 MinGW-w64(官网下载 installer,勾选 x86_64-posix-seh 和 add to PATH)xcode-select --install 装命令行工具即可获得 clang++;如需 g++,用 brew install gcc,注意装完后 g++-14 这类带版本号的命令才是真实可执行名g++ --version 或 clang++ --version,必须有输出;如果提示 command not found,请先解决 PATH 问题光靠默认界面写 C++ 是纯文本编辑,关键功能全靠扩展补足。
C/C++(Microsoft 官方扩展,提供智能提示、跳转、定义查看,依赖 c_cpp_properties.json 配置头文件路径)CMake Tools(如果你用 CMake 构建,它能自动检测 CMakeLists.txt 并生成构建目录)Code Runner(快速右键运行单文件,适合练手,但它绕过 tasks.json,不适合多文件项目)tasks.json 定义 VS Code 怎么调用编译器,不配它,Ctrl+Shift+B 就是摆设。
Ctrl+Shift+P → 输入 “Tasks: Configure Task” → 选 “Create tasks.json file from template” → 选 “Others”g++ 的最小可用配置(注意 args 中的 -g 必须加,否则 launch.json 调试会失败):{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": ["$gcc"],
"group": "build"
}
]
}
"command": "/usr/bin/g++" 改成 "command": "g++"(前提是 MinGW 已加进系统 PATH).cpp 文件,args 需扩展为 "${fileDirname}/*.cpp" 或改用 CMake没有 launch.json,点调试按钮只会弹窗说 “Please configure a launch configuration”。它和 tasks.json 是绑定关系——preLaunchTask 必须与 tasks.json 里 label 完全一致。
Ctrl+Shift+P → 输入 “Debug: Open launch.json” → 选 “C++ (GDB/LLDB)” → 选 “g++ build and debug active file”launch.json 中 program 字段是否指向编译产出的可执行文件(如 "${fileDirname}/${fileBasenameNoExtension}"),且 preLaunchTask 值和 tasks.json 中 label 严格匹配clang++ 编译,launch.json 的 miDebuggerPath 可能需设为 "lldb";Linux 下通常用 "gdb"
tasks.json 没加 -g 参数,或 launch.json 的 program 路径写错了最易被忽略的一点:每次换编译器(比如从 g++ 切到 clang++)、换操作系统、甚至升级了 MinGW 版本,都要重新核对 tasks.json 的 command 和 args——路径、参数名、输出格式都可能变。别迷信网上抄来的配置,始终以 g++ --help 输出为准。