如何在 Visual Studio Code 中编译并运行 C++ 源文件

Roc*_*645 5 c++ visual-studio-code

我一直在寻找这个问题的答案,但似乎找不到。我知道我们可以使用 task.json 文件来自动化构建过程。但我想使用 Visual Studio Code 在 C++ 中实现算法以进行竞争性编程。我希望能够编译一个程序,并在没有任何错误的情况下一次性运行它。如果有错误,我希望将它们显示出来。

另外,Visual Studio Code 附带一个集成终端,因此如果可以将程序输出重定向到那里就好了。另外,我们如何映射键盘快捷键来运行此任务。

我在 Windows 10 上使用 Visual Studio Code 2019 和 MinGW G++ 编译器。

编辑

我在下面尝试了 Escape0707 的答案,并尝试'Run Code'使用默认键绑定执行Ctrl + Alt + N,但出现此错误。

在此输入图像描述

Esc*_*707 4

更新了结合makevscode-cpptools调试的方法:

如果您不关心 VSCode 集成调试工具,它可以让您设置断点、在运行时更改变量值、检查变量值等,并且您想要一种更容易、更简单、更快、透明的调用方式好的旧命令行工具,请跳过本节并Code Runner在下面查看。

VSCode C++ 扩展附带的默认配置对于低端机器来说有点慢。最糟糕的是,他们总是会重建您的可执行文件,并且不支持“启动而不调试”。下面是 Linux(当然还有远程 WSL)的解决方法。

为了解决第一个问题,您设置make(对于简单的一个源文件编译,您只需要安装 make)来构建源代码,并在tasks.json. 为了解决第二个问题,您创建另一个任务,以便在第一个任务完成后运行构建的可执行文件:

使用 Intellisense 了解配置中的每个属性。

tasks.json

{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "presentation": {
    "clear": true,
    "focus": true,
    "panel": "shared"
  },
  "tasks": [
    {
      "label": "make active file",
      "type": "shell",
      "command": "make",
      "args": ["${fileBasenameNoExtension}.out"],
      "problemMatcher": "$gcc",
      "group": {
        "kind": "build",
        "isDefault": true
      }
    },
    {
      "label": "run active file executable without debuging",
      "type": "shell",
      "command": "${fileDirname}/${fileBasenameNoExtension}.out",
      "presentation": {
        "clear": false
      }
    },
    {
      "label": "make and run active file without debuging",
      "group": {
        "kind": "test",
        "isDefault": true
      },
      "dependsOn": [
        "make active file",
        "run active file executable without debuging"
      ],
      "dependsOrder": "sequence"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

要以这种方式使用 VSCode 进行调试,首先确保您-g在.CXXFLAGSMakefile

有关如何编写 a 的快速信息Makefile,请参阅、或、或。或者检查这个答案的最后一部分。

然后,创建以下内容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": "make and debug active file",
      "type": "cppdbg",
      "request": "launch",
      "program": "${fileDirname}/${fileBasenameNoExtension}.out",
      "cwd": "${workspaceFolder}",
      "setupCommands": [
        {
          "description": "Enable pretty-printing for gdb",
          "text": "-enable-pretty-printing",
          "ignoreFailures": true
        }
      ],
      "preLaunchTask": "${defaultBuildTask}"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

现在您可以使用命令面板来尝试Task: Run Build Task,,Task: Run Test TaskDebug: Start Debugging


原答案

请考虑Code Runner,因为它(对我来说)似乎比 VSCode 的内置调试程序(用于练习许多小型 C++ 代码文件)更快。我将描述如何使用该扩展来满足类似的要求。

  1. 确保您已将其PATH配置为包含clang++,以便可以从集成终端调用它。

    您还可以使用下面的g++替换。我更喜欢它,因为它为像我这样的 C++ 初学者提供了更严格的检查。clang++g++clang++

  2. 安装扩展。
  3. 在 VSCode 中settings.json,考虑添加以下条目:
    "code-runner.clearPreviousOutput": true,
    "code-runner.preserveFocus": false,
    "code-runner.runInTerminal": true,
    "code-runner.saveFileBeforeRun": true
    
    Run Code Online (Sandbox Code Playgroud)
  4. 并将最后一个自定义添加code-runner.executorMap到用户/工作空间设置,该设置描述当当前文件名的扩展名满足指定的扩展名时您希望扩展名发送到终端的命令。例如:
    "code-runner.executorMap": {
        "cpp": "\b\b\b\b\b\b\b\b\b\bclang++ -std=c++17 $fileName -o a.out && ./a.out"
    },
    
    Run Code Online (Sandbox Code Playgroud) 上面的设置告诉扩展程序,“当看到文件时.cpp,发送 10Backspace到终端(以删除任何错误输入的字符)并调用clang++ -std=c++17 *filename* -o a.out && ./a.out.

    我在 Linux 机器上使用此命令,对于 Windows,尝试将输出文件的文件扩展名更改为.exe并使用.\a.exe或 简单地调用它a.exe

  5. 最后,将Run Code命令映射到 VSCode 键盘快捷键设置中您首选的键绑定。我的是将其绑定到F5原来绑定到的Debug: Continue

快乐编码!


更新关于make

继续阅读以了解如何避免冗余编译过程并利用GNU make. 我将在 Linux 上执行此操作,并且仅针对 C++,因为我没有make在 Windows 或 OS X 上使用过,并且 C++ 最适合 ACM。

  1. 确保make已安装并在您的PATH
  2. 在您调用的同一目录下创建一个名为Makefile(或)的文件。(或在另一个目录中)。makefilemakemake -f /path/to/Makefile
  3. 将编译器选项重新定义为您喜欢的任何内容Makefile,例如:
    CXX = clang++
    CXXFLAGS = -std=c++17 -g -Weverything -Werror
    
    Run Code Online (Sandbox Code Playgroud)
  4. *.out为中创建自动定位规则Makefile,即:
    %.out: %.cpp
        $(LINK.cpp) $^ $(LOADLIBES) $(LDLIBS) -o $@
    
    Run Code Online (Sandbox Code Playgroud)

    注意:Tab第二行缩进必须使用s,而不是Spaces。

  5. 改成code-runner.executorMap
    CXX = clang++
    CXXFLAGS = -std=c++17 -g -Weverything -Werror
    
    Run Code Online (Sandbox Code Playgroud)
  6. (可选)*.out忽略git
    %.out: %.cpp
        $(LINK.cpp) $^ $(LOADLIBES) $(LDLIBS) -o $@
    
    Run Code Online (Sandbox Code Playgroud)
  7. (可选)要*.out在当前目录中删除:
    "code-runner.executorMap": {
        "cpp": "\b\b\b\b\b\b\b\b\b\bmake $fileNameWithoutExt.out && ./$fileNameWithoutExt.out"
    
    Run Code Online (Sandbox Code Playgroud)

现在,该Run Code命令将调用make并且仅当相应文件比该文件新时make才会重新生成文件,从而允许我们跳过编译并更顺利地进行测试。.out.cpp.out

CXXFLAGS针对 C++ 编译器选项,CFLAGS是针对 C 编译器选项。make -p您可以使用、Google 和GNU make手册#Automatic-Variables找到其他语言编译器选项及其变量名称。