Visual Studio Code 如何 Debug调试 CPP项目

本文由 ChatGPT 生成

Here’s a clean, practical way to set up C/C++ debugging in VS Code on Windows (since you’re using cl.exe and MSVC).


🧰 1. Install required tools

✅ Install:

  • Visual Studio Code
  • C/C++ Extension (Microsoft)
  • MSVC toolchain from Visual Studio 2022 (you already have it ✔)

⚙️ 2. Make sure MSVC environment is loaded

cl.exe only works inside the Developer Command Prompt.

👉 Either:

  • Launch VS Code from:

    x64 Native Tools Command Prompt for VS 2022
    code .
    

OR

  • Use vcvars64.bat inside tasks (more advanced)

🏗️ 3. Create build task (tasks.json)

Press:

Ctrl + Shift + P → "Tasks: Configure Task"

Example:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "build with cl",
      "type": "shell",
      "command": "cl",
      "args": [
        "/Zi",
        "/MDd",
        "/Od",
        "main.cpp",
        "/Fe:main.exe"
      ],
      "group": {
        "kind": "build",
        "isDefault": true
      },
      "problemMatcher": ["$msCompile"]
    }
  ]
}

🔑 Important flags:

  • /Zi → debug symbols
  • /Od → disable optimization
  • /MDd → match your Box2D build

🐞 4. Create debug config (launch.json)

Press:

F5 → "C++ (Windows)"

Then edit:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug (MSVC)",
      "type": "cppvsdbg",
      "request": "launch",
      "program": "${workspaceFolder}/main.exe",
      "args": [],
      "cwd": "${workspaceFolder}",
      "preLaunchTask": "build with cl",
      "stopAtEntry": false
    }
  ]
}

▶️ 5. Run debugger

Press:

F5

You can now:

  • set breakpoints
  • step (F10, F11)
  • inspect variables

🔍 Common issues (very relevant to you)

❗ Breakpoints not hit

➡ You forgot /Zi


❗ Symbols not loaded

➡ Make sure .pdb file is generated


👍 Minimal working mental model

  • tasks.jsonhow to build
  • launch.jsonhow to run/debug
  • /Zi → enables debugging
  • /MDd → must match all libs (your earlier issue!)

posted @ 2026-04-13 01:43  dewxin  阅读(12)  评论(0)    收藏  举报