在 Windows 上配置 VS Code C/C++ 环境

401 字
2 分钟
在 Windows 上配置 VS Code C/C++ 环境

目标#

在 Windows 上安装可维护的 GCC/GDB 工具链,并让 VS Code 能编译、运行和调试一个 C++ 程序。

前置条件#

  • 安装当前稳定版 VS Code。
  • 从官方站点安装 MSYS2。
  • 在 VS Code 扩展市场安装 Microsoft 发布的 C/C++ 扩展。

旧版 MinGW 安装器长期未更新。MSYS2 提供持续维护的 MinGW-w64 软件包和包管理器,更适合新环境。

安装工具链#

打开 MSYS2 UCRT64 终端,先按官网提示更新系统,再安装工具链:

pacman -Syu
pacman -S --needed base-devel mingw-w64-ucrt-x86_64-toolchain

将 C:\msys64\ucrt64\bin 添加到当前用户的 Path,重新打开 PowerShell 后验证:

g++ --version
gdb --version

如果 MSYS2 安装在其他目录,应使用实际的 ucrt64\bin 路径。

创建示例程序#

用 VS Code 打开一个空文件夹,创建 main.cpp:

#include <iostream>

int main() {
    std::cout << "Hello, C++!\n";
    return 0;
}

在终端先直接验证编译器:

g++ -std=c++20 -Wall -Wextra -g main.cpp -o main.exe
.\main.exe

输出应为 Hello, C++!。

配置构建任务#

创建 .vscode/tasks.json:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "build active C++ file",
      "type": "shell",
      "command": "g++",
      "args": [
        "-std=c++20",
        "-Wall",
        "-Wextra",
        "-g",
        "${file}",
        "-o",
        "${fileDirname}\\${fileBasenameNoExtension}.exe"
      ],
      "group": { "kind": "build", "isDefault": true },
      "problemMatcher": ["$gcc"]
    }
  ]
}

按 Ctrl+Shift+B 构建当前文件。

配置调试#

创建 .vscode/launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug active C++ file",
      "type": "cppdbg",
      "request": "launch",
      "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
      "cwd": "${fileDirname}",
      "MIMode": "gdb",
      "miDebuggerPath": "C:\\msys64\\ucrt64\\bin\\gdb.exe",
      "preLaunchTask": "build active C++ file"
    }
  ]
}

在 main() 内设置断点并按 F5。如果找不到动态库,确认 VS Code 进程读取到了更新后的 Path。

验证清单#

  1. PowerShell 中能运行 g++ 和 gdb。
  2. Ctrl+Shift+B 生成 .exe 文件且无警告。
  3. F5 能停在断点,并可查看局部变量。

参考#

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

在 Windows 上配置 VS Code C/C++ 环境
https://blog.mintalix.com/posts/github-vscode-c-cpp/
作者
Mint
发布于
2020-09-13
许可协议
CC BY-NC-SA 4.0

评论区

Profile Image of the Author
Mint
软件开发、工程实践与技术思考。
分类
标签