【问题标题】:How to compile and run a c++ source file in visual studio code如何在 Visual Studio 代码中编译和运行 C++ 源文件
【发布时间】:2019-10-10 05:08:58
【问题描述】:

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

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

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

编辑

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

【问题讨论】:

  • 嗯,你怎么错过了这个:code.visualstudio.com/docs/cpp/config-mingw
  • 该教程只描述了如何编译我的程序,而不是如何使用简单的快捷方式编译和运行它。我想知道如何编辑 tasks.json 文件来实现这种效果。
  • Windows 上的输出名称应为“a.exe”。 (Windows 表示文件是带有“.exe”后缀的可执行文件;Linux 使用文件系统属性。)
  • CTRL + SHIFT + B 构建,F5 在调试器中运行。另外,也许 Visual Studio 2019 社区版可能更适合您?

标签: c++ visual-studio-code


【解决方案1】:

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

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

VSCode C++ 扩展的默认配置对于低端机器来说有点慢。最糟糕的是,他们总是会重建您的可执行文件和don't support 'Start Without Debugging'。以下是适用于 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"
    }
  ]
}

要以这种方式使用 VSCode 进行调试,首先确保在 Makefile 中将 -g 编译标志添加到 CXXFLAGS

有关如何编写Makefile 的快速信息,请参阅thisthisthis。或查看此答案的最后一部分。

然后,创建以下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 TaskTask: Run Test TaskDebug: Start Debugging


原答案

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

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

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

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

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

  5. 最后,将Run Code 命令映射到您在 VSCode 的键盘快捷键设置中的首选键绑定。我的是将它绑定到最初绑定到Debug: ContinueF5

编码愉快!


关于make的更新

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

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

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

  5. code-runner.executorMap 更改为:
    "code-runner.executorMap": {
        "cpp": "\b\b\b\b\b\b\b\b\b\bmake $fileNameWithoutExt.out && ./$fileNameWithoutExt.out"
    
  6. (可选)为 git 忽略 *.out
    echo "*.out" >> .gitignore
    
  7. (可选)删除当前目录中的*.out
    rm *.out
    

现在Run Code 命令将调用make 并且make 将仅在对应的.cpp 文件比.out 文件更新时重新生成.out 文件,从而允许我们跳过编译并继续测试更流畅。

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

【讨论】:

  • 在哪里可以找到 settings.json 文件?在这个网站上:code.visualstudio.com/docs/getstarted/settings 它说我可以在:%APPDATA%\Code\User\settings.json 找到它,但我似乎找不到 Code 文件夹。
  • 有一个Open Settings (JSON)按钮位于Settings标签的右上角,按Ctrl+,打开。第三步的settings.json,也可以按Ctrl+Shift+P搜索Preferences: Open Settings (JSON)
  • 我只使用 JSON 来描述我的自定义,以便在 Stack Overflow 上轻松发短信。您可以直接在设置选项卡 UI 中更改相应的设置。
  • 谢谢,我试过了,但现在我得到了一个不同的错误,我已经更新了我的问题来显示它。
  • 我的示例针对我的 Arch Linux 系统,我的编译器的输出文件可以使用./filename 运行。然而,在 Windows 上,您应该提供输出文件名 a.exe 等。然后通过调用 .\a.exea.exe 运行它。我将编辑我的答案以注意我使用的操作系统。
【解决方案2】:

要在 VS 代码中构建/运行 C++ 项目,您需要手动配置工作区文件夹中 .vscode 文件夹中的 tasks.json 文件。要打开tasks.json,请按ctrl + shift + P,然后输入配置任务,然后按回车,它将带您到tasks.json

这里我给我的tasks.json文件提供了一些cmets,让文件更容易理解,可以作为配置tasks.json的参考,希望对你有用

配置tasks.json后,编译运行你的c++文件,按ctrl+shift+B,这是在vscode中运行构建工具的快捷方式。您的 C++ 程序现在将仅在 vscode 集成终端上运行。 如果这会出现一些问题,请将默认终端更改为 cmd(默认情况下它在 Windows 中是 powershell)并确保文件路径中没有任何空格。

tasks.json

{
    "version": "2.0.0",

    "tasks": [

        {
            "label": "build & run",     //It's name of the task , you can have several tasks 
            "type": "shell",    //type can be either 'shell' or 'process' , more details will be given below
            "command": "g++",   
            "args": [
                "-g",   //gnu debugging flag , only necessary if you want to perform debugging on file  
                "${file}",  //${file} gives full path of the file
                "-o",   
                "${workspaceFolder}\\${fileBasenameNoExtension}",    //output file name
                "&&",   //to join building and running of the file
                "${workspaceFolder}\\${fileBasenameNoExtension}"
            ],
            "group": {
                "kind": "build",    //defines to which group the task belongs
                "isDefault": true
            },
            "presentation": {   
                "echo": false,
                "reveal": "always",
                "focus": true,
                "panel": "shared",
                "clear": false,
                "showReuseMessage": false
            },
            "problemMatcher": "$gcc"
        },

    ]
}

tasks.jsonpresentation 中的所有属性仅用于根据您的需要自定义构建任务,请随意将它们更改为您最喜欢的。您可以在 vscode tasks documentations

上阅读有关演示文稿属性(和其他内容)的信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多