VSCode+MinGW(MSYS2) C++环境搭建

维基百科 MinGW
MinGWMinimalist GNU for Windows),又称mingw32,是将GCC编译器和GNU Binutils移植到Win32平台下的产物,包括一系列头文件(Win32API)、可执行文件
另有可用于产生32位及64位Windows可执行文件的MinGW-w64项目,是从原本MinGW产生的分支[1]。如今已经独立发展[2]

MSYS2
MSYS2 is a software distro and building platform for Windows
It provides a bash shell, Autotools, revision control systems and the like for building native Windows applications using MinGW-w64 toolchains.
It features a package management system to provide easy installation of packages, Pacman. It brings many powerful features such as dependency resolution and simple complete system upgrades, as well as straight-forward package building.

  • 安装MinGW

这里采用安装msys,再由msys安装minGW的方式
使用 https://blog.csdn.net/qiuzhiqian1990/article/details/56671839 里的方法
官网下载可能非常慢,可以从清华镜像源(tuna)下载,https://mirrors.tuna.tsinghua.edu.cn/msys2/distrib/x86_64
安装完成后,将所安装的mingw下的bin路径添加到环境变量PATH中,一般是<msys安装路径>/<mingw64 或 mingw32>/bin,这样在任何路径下都可以使用gcc gdb等各命令

  • 配置VSCode

安装扩展

  • C/C++
    用于代码提示和补全
  • Code Runner
    用于生成(build)并运行(run)

安装完成后须点击重新加载或重启VSCode

更改设置

打开用户设置,加入如下项

    // 生成 build & 运行 run  若已使用 Code Runner,注意和已有设置的关系
    // Whether to run code in Integrated Terminal.
    "code-runner.runInTerminal": true,
    // Set the executor of each language.
    "code-runner.executorMap": {
        "c": "cd $dir && gcc $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
        "cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
    },

    // Set the executor of each file extension.
    "code-runner.executorMapByFileExtension": {
    },

现在,可以在VSCode中打开一个文件夹,打开里面的一个源文件,ctrl+shift+p打开命令面板,运行其中的 Run Code,该源文件将被编译生成目标文件,并在VSCode里的终端中运行
也可使用 Code Runner 的默认快捷键ctrl+shift+n,如果该快捷键之前没有被占用

    // 调试 debug
    "launch": {
        "configurations": [
            {
                "name": "(gdb) Launch",
                "type": "cppdbg",
                "request": "launch",
                "program": "${workspaceFolder}/${fileBasenameNoExtension}",
                "args": [],
                "stopAtEntry": false,
                "cwd": "${workspaceFolder}",
                "environment": [],
                "externalConsole": true,
                "MIMode": "gdb",
                "miDebuggerPath": "gdb.exe",
                "setupCommands": [
                    {
                        "description": "Enable pretty-printing for gdb",
                        "text": "-enable-pretty-printing",
                        "ignoreFailures": true
                    }
                ]
            }
        ],
        "compounds": []
    },

现在,可以f5进行运行调试

推荐阅读更多精彩内容