2025年9月9日星期二

Vs code 編譯執行設定

步驟一:安裝 C/C++ 延伸模組與編譯器

安裝延伸模組:在 VS Code 中,開啟延伸模組市集(Ctrl+Shift+X),搜尋並安裝 C/C++ 延伸模組(由 Microsoft 提供)。
安裝編譯器:
如果使用的是 Windows,請安裝 MinGW-w64。
在安裝完成後,將編譯器路徑(通常是 C:\MinGW\bin 或 C:\mingw64\bin)加入到系統的 PATH 環境變數中。

步驟二:建立與設定 tasks.json

tasks.json 用於告訴 VS Code 如何編譯您的程式。它會被用來建置專案,也會在除錯前自動執行。
開啟專案資料夾後,按下 Ctrl+Shift+P,輸入 Tasks: Configure Task,然後選擇 Create tasks.json from template -> Others。
用以下內容覆蓋新生成的 tasks.json 檔案,這是一個專為您專案設計的多檔案編譯任務:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build my project",
            "type": "shell",
            "command": "gcc",
            "args": [
                "-g",
                "${workspaceFolder}/main.c",              // 加入編譯檔案
                "${workspaceFolder}/array_handler.c",// 加入編譯檔案
                "-o",
                "${workspaceFolder}/main.exe"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                "echo": true,
                "reveal": "always",
                "focus": false,
                "panel": "shared",
                "showReuseMessage": false
            },
            "problemMatcher": ["$gcc"],
            "detail": "Builds the main.c and array_handler.c files."
        }
    ]
}

名稱功能說明

label: build my project 是您任務的名稱,這個名稱稍後會被 launch.json 引用。
args: 使用 ${workspaceFolder} 確保編譯器能從專案根目錄正確找到 main.c 和 array_handler.c。
group: 將此任務設為預設的建置(build)任務,這樣您可以直接使用 Ctrl+Shift+B 來執行。

步驟三:建立與設定 launch.json
launch.json 用於配置除錯器。它會指定如何啟動您的程式,並連結到 tasks.json 進行建置。
進入除錯視圖(Ctrl+Shift+D),點選左上角的「Run and Debug」按鈕,然後從下拉選單中選擇 C++ (GDB/LLDB)。
VS Code 會自動生成一個 launch.json 檔案。用以下內容覆蓋它:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug my project",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/main.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": true,
            "MIMode": "gdb",
            "miDebuggerPath": "C:\\MinGW\\bin\\gdb.exe", // 根據安裝路徑修改
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "build my project"
        }
    ]
}


步驟四:編譯與執行
完成以上設定後,依序點擊下圖。VS Code 會先自動執行編譯任務,然後啟動除錯器並執行程式。



沒有留言:

發佈留言

打賞按讚