VSCode 配置一键运行与 Debug

本文首发于我的个人博客:Sui Xin’s Blog
原文:https://suixinblog.cn/2019/09/vscode-code-runner-debug.html
作者:Sui Xin

本文以 Python 和 C++ 为例,在 VSCode 中配置多语言一键运行和 Debug 环境。

Code Runner

插件中心搜索并安装 Code Runner,安装完成后只需简单配置即可使用。
默认使用快捷键 ⌃⌥N 来运行脚本,使用 ⌃⌥M 来结束运行。

配置多语言执行命令

在 VSCode 设置中搜索 Code Runner,找到 Code-runner: Executor Map,点击 Edit in settings.json 打开系统设置文件,添加如下设置:

"code-runner.executorMap": {
        "python": "python3 $fullFileName",
        "cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt -g && $dir$fileNameWithoutExt"
    }

可根据自身需求进行更改,上述代码配置的 C++ 是编译后直接运行可执行文件的。
其中,根据官网,可使用的变量有:

  • $workspaceRoot: The path of the folder opened in VS Code
  • $dir: The directory of the code file being run
  • $dirWithoutTrailingSlash: The directory of the code file being run without a trailing slash
  • $fullFileName: The full name of the code file being run
  • $fileName: The base name of the code file being run, that is the file without the directory
  • $fileNameWithoutExt: The base name of the code file being run without its extension
  • $driveLetter: The drive letter of the code file being run (Windows only)
  • $pythonPath: The path of Python interpreter (set by Python: Select Interpreter command)

让程序在内置终端下运行

默认的 Code Runner 会在 OUTPUT 标签页下运行,在设置中将 Code-runner: Run In Terminal 打开即可修改为在内置终端下运行。

Debug

为了能够在全局下使用定义的 Debug,我们直接在 VSCode 的设置文件中设置 Debug 配置(settings.json 可在 UI 设置右上角点击打开)。
settings.json 中添加如下设置:

"launch": {
        "version": "0.2.0",
        "configurations": [
            {
                "name": "C++",
                "type": "cppdbg",
                "request": "launch",
                "targetArchitecture": "x86",
                "program": "${fileDirname}/${fileBasenameNoExtension}",
                "args": [],
                "stopAtEntry": false,
                "cwd": "${workspaceFolder}",
                "environment": [],
                "MIMode": "lldb"
            },
            {
                "name": "Python",
                "type": "python",
                "request": "launch",
                "program": "${file}",
                "console": "integratedTerminal"
            }
        ]
    }

保存退出即可。默认按 F5 即可调试代码。

参考

https://code.visualstudio.com/docs/editor/debugging#_global-launch-configuration

你可能感兴趣的:(Tools,Python,C++,VSCode)