c++ - 如何在 Visual Studio 代码中编译和运行 C++ 源文件

标签 c++ visual-studio-code

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

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

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

编辑

我在下面尝试了 Escape0707 的答案,并尝试执行 'Run Code'使用默认键绑定(bind) Ctrl + Alt + N但我收到了这个错误。

enter image description here

最佳答案

更新了结合 make 的方法和 vscode-cpptools调试:
如果您不关心 VSCode 集成调试工具,它可以让您设置断点、在运行时更改变量值、检查变量值等,并且您想要一种更简单、更简单、更快、更透明的调用方式好的旧命令行工具,跳过本节并查看 Code Runner以下。
VSCode C++ 扩展附带的默认配置对于低端机器来说有点慢。最糟糕的是,他们总是会重新构建您的可执行文件,并且 don't support 'Start Without Debugging' .以下是 Linux(当然还有远程 WSL)的解决方法。
为了解决第一个问题,您设置 make (对于简单的一个源文件编译你只需要安装make)来构建你的源代码,并在tasks.json中设置构建任务.为了解决第二个问题,您创建另一个任务只是为了在第一个任务完成后运行构建的可执行文件:

Use Intellisense to learn about each properties in configs.


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"
    }
  ]
}
要以这种方式使用 VSCode 进行调试,首先确保添加了 -g编译标志为CXXFLAGSMakefile .

For quick information about how to write a Makefile, see this, or this, or this. Or check this last part of this answer.


然后,创建以下 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}"
    }
  ]
}
现在您可以使用命令调色板尝试Task: Run Build Task , Task: Run Test Task , Debug: Start Debugging .

原始答案
请考虑 Code Runner ,因为它似乎比 VSCode 的内置调试过程更快(对我来说),用于练习许多小型 C++ 代码文件。我将描述我如何使用该扩展来满足类似的要求。
  • 确保您已配置 PATH包括clang++因此您可以从集成终端调用它。

    You can also use g++ by substitute clang++ below with g++. I prefer clang++ as it provides stricter checks for C++ beginners like me.


  • 安装扩展。
  • 在你的 VSCode 的 settings.json ,请考虑添加以下条目:
    "code-runner.clearPreviousOutput": true,
    "code-runner.preserveFocus": false,
    "code-runner.runInTerminal": true,
    "code-runner.saveFileBeforeRun": true
    
  • 并添加最后的自定义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"
    },
    
    上面的设置告诉扩展,“当看到 .cpp 文件时,发送 10 Backspace 到终端(删除任何输入错误的字符)并调用 clang++ -std=c++17 *filename* -o a.out && ./a.out

    I use this command on my Linux machine, for Windows, try change the filename extension of the output file to .exe and invoke it with .\a.exe or simply a.exe.


  • 最后,映射Run Code命令到 VSCode 的键盘快捷键设置中的首选键绑定(bind)。我的是将它绑定(bind)到最初绑定(bind)到 Debug: Continue 的 F5 .

  • 快乐编码!

    更新关于 make继续阅读以了解如何利用 GNU make 避免冗余编译过程并加快案例测试.我将在 Linux 上执行此操作,并且仅针对 C++,因为我没有使用 make在 Windows 或 OS X 和 C++ 上最适合 ACM。
  • 确保 make已安装并在您的 PATH
  • 创建一个名为 Makefile 的文件(或 makefile )在您调用 make 的同一目录下. (或在另一个目录和 make -f /path/to/Makefile 中)。
  • Makefile 中将编译器选项重新定义为您喜欢的任何内容,例如:
    CXX = clang++
    CXXFLAGS = -std=c++17 -g -Weverything -Werror
    
  • *.out 创建自动目标规则在 Makefile , IE。:
    %.out: %.cpp
        $(LINK.cpp) $^ $(LOADLIBES) $(LDLIBS) -o $@
    

    Attention: must use Tab to indent the second line, not Spaces.


  • 更改code-runner.executorMap到 :
    "code-runner.executorMap": {
        "cpp": "\b\b\b\b\b\b\b\b\b\bmake $fileNameWithoutExt.out && ./$fileNameWithoutExt.out"
    
  • (可选)忽略 *.out对于 git :
    echo "*.out" >> .gitignore
    
  • (可选)删除 *.out在当前目录中:
    rm *.out
    

  • 现在Run Code命令将调用 makemake只会重新生成 .out文件时对应.cpp文件比 .out 更新文件,因此允许我们跳过编译并进行更顺畅的测试。

    The CXXFLAGS is for C++ compiler options, CFLAGS is for C compiler options. You can find other language compiler options and their variable name using make -p, Google and GNU make manual#Automatic-Variables.

    关于c++ - 如何在 Visual Studio 代码中编译和运行 C++ 源文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58315780/

    相关文章:

    c++ - 为什么可执行文件这么大? (为什么不删除死代码?)

    c++ - 具有特征参数的模板特化函数

    java - 无法在VScode中创建Maven项目: "Program ' cmd' failed to run"

    android - Flutter VSCode:调试错误:无法使用BuildSessionServices.createFileHasher()创建FileHasher类型的服务

    C++ 应用程序 : How to properly delete/release an allocated object?

    c++ - 使用 pthread 计算平均运行时间,结果很奇怪

    c++ - 如何检查路径在 boost::filesystem 中是否有效?

    css - 在 Visual Studio Code 的 CSS 文件中启用供应商前缀自动完成

    javascript - 在 Visual Code 中筛选/排序 IntelliSense 建议

    python-3.x - VS 代码 : "Property Debug Options Not Allowed"