如何在Visual Studio Code中使用MinGW编译和调试C++代码

本文指导如何在Visual Studio Code(VSCode)中配置C++的调试环境,包括安装MinGW,创建并配置tasks.json和launch.json文件,以及启用自动补全功能。详细步骤涵盖了从打开项目到编译、调试和设置自动补全的全过程,确保开发者能够顺利进行C++代码的开发和调试。

为了在VS Code中调试代码,首先需要安装VS Code和MinGW,参考文章Command line配合MinGW
接下来是具体设置:
1.打开cmd,cd至项目目录,键入code .,在VS Code中打开项目;
2.VS Code中使用快捷键Ctr+Shift+P,打开控制面板输入Terminal > Configure Default Build Task,选择g++.exe build active file, 会创建tasks.json文件,这个文件用于配置编译选项。
设置
3.设置tasks.json内容如下:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
      {
        "type": "shell",
        "label": "C/C++: g++.exe build active file", // 任意取名
        "command": "C:\\MinGW\\bin\\g++.exe",  //此处修改为MinGW的g++.exe路径
        "args": [
          "-g",  // g++的调试选项
          "-std=c++11",  // c++版本
          "MFC.CPP", // 源文件1
          "MY.CPP", // 源文件2
          "-o",
          "TEST.exe"  // 输出文件,默认值为${fileDirname}\\${fileBasenameNoExtension}.exe, 是入口函数所在文件名称,第一个cpp文件,如main.cpp
        ],
        "options": {
          "cwd": "${workspaceFolder}"
        },
        "problemMatcher": [
          "$gcc"
        ],
        "group": {
          "kind": "build",
          "isDefault": true
        }
      }
    ]
}

保存编辑。

4.创建launch.json文件
在VS Code主窗口左侧Run选项(Ctr + Shift + D),选择Add Configuration,选择C++ (GDB/LLDB),接着选择 g++.exe build and debug active file.
Run
创建launch.json文件launch.json
此时会创建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": "(gdb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "C:\\Users\\ITadmin\\Desktop\\Test\\MFC\\FRAME2.03\\TEST.exe", // 调试入口程序
            //可以使用${workspaceFolder}/main.exe来使用工作区路径为base path
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "C:\\MinGW\\bin\\gdb.exe", // gdb.exe安装路径
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ]
        }
    ]
}

5.回到主程序 (main函数)文件,使用Ctr + Shift + B来编译代码:
编译
有时编译出错提示找不到源文件,这时要检查当前工作目录cwd是否是project目录。
工作目录

无错误情况如图。按“+”键创建一个新的terminal。

6.在程序中设置断点,点击Run,切换至调试模式,点击“(gdb) Launch" 开始调试。
调试
7.配置自动补全功能
使用Ctr + Shift + P打开命令选板,选择C/C++: Edit Configurations (UI)创建c_cpp_properties.json文件,这个文件用于设置自动补全功能,配置如下

{
    "configurations": [
        {
            "name": "GCC",
            "includePath": [
                "${workspaceFolder}/**",
                "C:\\MinGW\\include"  // MinGW include 目录
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "windowsSdkVersion": "10.0.18362.0",
            "compilerPath": "C:\\MinGW\\bin\\g++.exe", //MinGW编译器路径
            "cStandard": "c11",
            "cppStandard": "c++11",  // c++标准
            "intelliSenseMode": "gcc-x64" //将默认的MSVC mode改为gcc mode
        }
    ],
    "version": 4

参考文献:
Get Started with C++ and MinGW in Visual Studio Code
Debug C++ in Visual Studio Code
Configuring C/C++ debugging

### Visual Studio Code 配置 MinGW 教程 配置 Visual Studio Code(VSCode)以使用 MinGW 作为 C/C++ 编译器需要完成以下设置,包括安装 MinGW、配置环境变量以及调整 VSCode 的相关配置文件。 #### 1. 安装 MinGW 下载并安装 MinGW-w64 工具链。推荐从官方网站或 SourceForge 下载页面获取最新版本的 MinGW-w64,例如 `x86_64-14.2.0-release-win32-seh-ucrt-rt_v12`[^3]。将下载的压缩包解压到一个路径中,确保该路径不包含中文字符或空格,例如 `D:\mingw64`。 #### 2. 配置环境变量 将 MinGW 的 `bin` 目录添加到系统的环境变量 `PATH` 中,以便在命令行中直接调用 GCC 编译器。例如,如果 MinGW 解压到 `D:\mingw64`,则需将 `D:\mingw64\bin` 添加到 `PATH` 环境变量中[^3]。 验证安装是否成功,打开命令提示符并输入以下命令: ```bash gcc --version ``` 若显示 GCC 版本信息,则说明安装正确[^2]。 #### 3. 安装 VSCode 扩展 在 VSCode 中安装以下扩展以支持 C/C++ 开发: - **C/C++**:由 Microsoft 提供,用于 IntelliSense、调试代码浏览功能。 - **Code Runner**(可选):用于快速运行代码。 #### 4. 配置 `tasks.json` 在 VSCode 中创建或编辑 `tasks.json` 文件以定义编译任务。按下 `Ctrl+Shift+P`,搜索并选择 **Tasks: Configure Task**,然后选择 **Create tasks.json file from template** 并选择 **Others** 模板。编辑生成的 `tasks.json` 文件如下: ```json { "version": "2.0.0", "tasks": [ { "label": "build hello", "type": "shell", "command": "g++", "args": [ "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "group": { "kind": "build", "isDefault": true }, "problemMatcher": ["$gcc"] } ] } ``` 此配置表示使用 `g++` 编译当前文件,并生成与文件名相同的可执行文件[^3]。 #### 5. 配置 `launch.json` 为了支持调试功能,需要创建或编辑 `launch.json` 文件。按下 `Ctrl+Shift+D`,点击齿轮图标,选择 **C++ (GDB/LLDB)** 模板。编辑生成的 `launch.json` 文件如下: ```json { "version": "0.2.0", "configurations": [ { "name": "Launch Program", "type": "cppdbg", "request": "launch", "program": "${fileDirname}\\${fileBasenameNoExtension}.exe", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": true, "MIMode": "gdb", "miDebuggerPath": "D:\\mingw64\\bin\\gdb.exe", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true } ], "preLaunchTask": "build hello" } ] } ``` 此配置指定调试器为 GDB,并关联之前定义的编译任务。 #### 6. 测试配置 创建一个简单的 C++ 文件 `hello.cpp`: ```cpp #include <iostream> int main() { std::cout << "Hello, MinGW!" << std::endl; return 0; } ``` 按下 `F5` 启动调试,或者使用 `Ctrl+Shift+B` 运行编译任务后,在终端中运行生成的可执行文件。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值