Skip to content

在VSCode上写C/C++[极速版]

准备工作: 安装 C/C++ 和 CodeLLDB (调试用) 插件

编译运行

Command + Shift + P ,输入 Preferences: Open Settings (JSON) 并打开,更改 code-runner.executorMap 中的 C 和 Cpp 部分

"c": "cd $dir && clang $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
"cpp": "cd $dir && clang++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",

还可以加上:

"code-runner.runInTerminal": true,

避免输出一闪而过

调试

先按debug按钮 (推荐选clang)

截屏2025-03-21 21.24.24

目的只是生成 .vscode/tasks.json 文件:

{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: clang 生成活动文件",
            "command": "/usr/bin/clang",
            "args": [
                "-fcolor-diagnostics",
                "-fansi-escape-codes",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "调试器生成的任务。"
        }
    ],
    "version": "2.0.0"
}

文件中是编译C文件的一些命令,告诉VSCode怎么去编译 .c

然后我们在debug窗口选择 create a launch.json file,选 LLDB

截屏2025-03-21 21.34.59

此时生成 launch.json 文件,指示VSCode怎么去调试

{
    "version": "0.2.0",
    "configurations": [

        {
            "type": "lldb",
            "request": "launch",
            "name": "Debug",
            "program": "${workspaceFolder}/<executable file>",
            "args": [],
            "cwd": "${workspaceFolder}"
        }
    ]
}

要把 Line 9 的 <executable file> 改成之前tasks.json指导编译出的文件,也就是 ${fileBasenameNoExtension}

"program": "${workspaceFolder}/${fileBasenameNoExtension}",

launch.json 会对程序debug,但不会自动去生成可执行文件,所以还要加上 preLaunchTask 并拷贝 tasks.jsonlabel ,使得在调试之前能将源代码编译一遍。最终版如下:

{
    "version": "0.2.0",
    "configurations": [

        {
            "preLaunchTask": "C/C++: clang 生成活动文件",
            "type": "lldb",
            "request": "launch",
            "name": "Debug",
            "program": "${workspaceFolder}/${fileBasenameNoExtension}",
            "args": [],
            "cwd": "${workspaceFolder}"
        }
    ]
}

OK,现在就可以回到 hello.c,菜单窗口 Run $\rightarrow $ Start Debugging,或者 F5,就可以开始debug了

截屏2025-03-21 21.48.12

参考资料

B站|macOS VS Code C/C++ Debug