一、安装C/C++编译器

macOS和主流Linux系统都自带C/C++编译器,Windows系统需要通过安装mingw来获得C/C++编译器
(1)mingw下载地址:https://sourceforge.net/proje...

(2)安装完mingw后,将安装目录添加到用户变量和系统变量中的Path后。bin目录下的文件列表如图:

二、验证C/C++开发环境

打开命令行,输入gcc --verion和g++ --version。如果出现以下输出证明开发环境安装完成:

三、在VS Code中安装C++相关插件

打开VS Code,安装以下插件:
C/C++插件,由微软官方开发维护,提供了丰富的C和C++的开发支持
Code Runner插件:一键运行代码,支持40多种编程语言
CodeLLDB插件:一款用于调试C++的原生插件
由于网络问题,CodeLLDB可能无法在线安装,可以下载CodeLLDB对应的vsix文件进行离线安装

四、进入调试界面添加配置环境

(1)写代码的文件夹下创建了一个.vscode文件夹,.vscode有三个文件,内容如下:

(2)首次调试时,需添加配置环境,选择C++(GDB/LLDB),会自动生成launch.json配置文件

(3)编辑launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [

        {
            "name": "g++.exe 生成和调试活动文件",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": true,
            "MIMode": "gdb",
            "miDebuggerPath": "D:\\myMinGW\\minGW\\bin\\gdb.exe", // minGW的安装地址
            "setupCommands": [
                {
                    "description": "为 gdb 启用整齐打印",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "task g++" //修改项
        }
    ]
}

(4)返回cpp文件,按F5进行调试,会弹出:找不到任务“task g++”;这是选择配置任务,会自动生成tasks.json。编辑tasks.json文件

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "task g++",
            "type": "shell",
            "command": "D:\\myMinGW\\minGW\\bin\\g++.exe",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "D:\\myMinGW\\minGW\\bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": "build"
        }
    ]
}

注意,launch.json中preLaunchTask的值必须和tasks.json文件中label的值一样

(5)c_cpp_properties.json

{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "compilerPath": "D:\\myMinGW\\minGW\\bin\\g++.exe", //替换为实际安装目录
            "cStandard": "c17",
            "cppStandard": "c++17",
            "intelliSenseMode": "gcc-x64"
        }
    ],
    "version": 4
}

五、调试和运行成功

注意

如果调试运行时系统报错:g++ : 无法将“g++”项识别为 cmdlet;则可选择以管理员身份启动VS Code

03-05 23:13