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

5
我已经寻找了这个问题的答案,但似乎没有找到。我知道我们可以使用task.json文件来自动化构建过程。但我想使用Visual Studio Code在C++中实现算法以进行竞赛编程。如果没有错误,我希望能够编译程序并一次性运行它。如果有错误,我希望能够显示它们。
此外,Visual Studio Code带有集成终端,因此如果程序输出可以重定向到终端会很好。同时,我们如何将键盘快捷方式映射到运行此任务上。
我正在Windows 10上使用Visual Studio Code 2019和MinGW G++编译器。
编辑:
我尝试了Escape0707下面的答案,并尝试使用默认键绑定Ctrl + Alt + N执行'Run Code',但我得到了这个错误。

enter image description here


3
哦,你错过了这个:https://code.visualstudio.com/docs/cpp/config-mingw - Chef Gladiator
2
那个教程只是描述了如何编译我的程序,而没有说明如何使用简单的快捷方式编译和运行它。我想知道如何编辑tasks.json文件以实现这个效果。 - Rockstar5645
1
输出文件名应为“a.exe”,在Windows操作系统中,“.exe”后缀表示该文件是可执行文件;而Linux则使用文件系统属性来表示。 - molbdnilo
1
按下CTRL + SHIFT + B进行构建,按下F5进入调试器运行。另外,也许Visual Studio 2019社区版更适合您? - Chef Gladiator
2个回答

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"
    }
  ]
}

要使用VSCode进行调试,首先确保您已将-g编译标志添加到MakefileCXXFLAGS中。

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

然后,创建以下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}"
    }
  ]
}

现在您可以使用命令调色板尝试 任务:运行构建任务任务:运行测试任务调试:开始调试

原始回答

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

  1. Make sure you've configured your PATH to include clang++ so you can invoke it from the integrated terminal.

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

  2. Install the extension.
  3. In your VSCode's settings.json, consider adding the following entries:
    "code-runner.clearPreviousOutput": true,
    "code-runner.preserveFocus": false,
    "code-runner.runInTerminal": true,
    "code-runner.saveFileBeforeRun": true
    
  4. And add the last customization code-runner.executorMap to user/workspace setting that describes which command you would like the extension to send to the terminal when current filename's extension meets the specified ones. For example:
    "code-runner.executorMap": {
        "cpp": "\b\b\b\b\b\b\b\b\b\bclang++ -std=c++17 $fileName -o a.out && ./a.out"
    },
    
    The above setting tells the extension, "When see a .cpp file, send 10 Backspace to terminal (to delete any mistyped characters) and call 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.

  5. Finally, map the Run Code command to your preferred keybinding in VSCode's Keyboard Shortcuts settings. Mine is to bind it to F5 which is originally bound to Debug: Continue.

快乐编程!


有关make的更新

继续阅读,了解如何通过利用GNU make避免冗余编译过程并加速案例测试。我将在Linux上进行此操作,并仅限于C++,因为我没有在Windows或OS X上使用make,而C++是ACM最好的语言。

  1. Make sure make is installed and in your PATH
  2. Create a file named Makefile (or makefile) under the same directory you invoke make. (Or in another directory and make -f /path/to/Makefile).
  3. Redefine compiler options to whatever you like in the Makefile, e.g.:
    CXX = clang++
    CXXFLAGS = -std=c++17 -g -Weverything -Werror
    
  4. Create auto-target rule for *.out in the Makefile, i.e.:
    %.out: %.cpp
        $(LINK.cpp) $^ $(LOADLIBES) $(LDLIBS) -o $@
    

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

  5. Change code-runner.executorMap to :
    "code-runner.executorMap": {
        "cpp": "\b\b\b\b\b\b\b\b\b\bmake $fileNameWithoutExt.out && ./$fileNameWithoutExt.out"
    
  6. (Optional) To ignore *.out for git:
    echo "*.out" >> .gitignore
    
  7. (Optional) To remove *.out in current directory:
    rm *.out
    
现在,Run Code 命令将调用 make,当相应的 .cpp 文件比 .out 文件更新时,make 将只重新生成 .out 文件,使我们能够更加顺畅地跳过编译并进行测试。

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


1
我在哪里可以找到settings.json文件?在这个网站上:https://code.visualstudio.com/docs/getstarted/settings 上说我可以在%APPDATA%\Code\User\settings.json找到它,但是我似乎找不到Code文件夹。 - Rockstar5645
1
在按下 Ctrl+, 打开的 设置 选项卡的右上角,有一个名为 打开设置(JSON) 的按钮。对于第三步中的 settings.json,您也可以按 Ctrl+Shift+P 并搜索 首选项:打开设置(JSON) - Escape0707
1
我只使用JSON来描述我的自定义设置,以便在Stack Overflow上轻松地进行文本编辑。您可以直接在设置选项卡UI中更改相应的设置。 - Escape0707
1
谢谢,我尝试了这个方法,但现在出现了另一个错误,我已经更新了我的问题以展示它。 - Rockstar5645
1
我的示例针对我的 Arch Linux 系统,编译器的输出文件可以通过 ./filename 运行。然而,在 Windows 上,你应该给出输出文件名 a.exe,等等。并通过调用 .\a.exea.exe 来运行它。我会编辑我的答案来注意我使用的操作系统。 - Escape0707
@Rockstar5645 我已更新答案,使用了 GNU make。希望这能更好地帮助你。 - Escape0707

3
要在VS Code中构建/运行C++项目,您需要手动配置工作区文件夹中.vscode文件夹中的tasks.json文件。要打开tasks.json,请按ctrl + shift + P,然后输入配置任务,按Enter,它将带您进入tasks.json。
这里我提供了我的tasks.json文件,并添加了一些注释,以使该文件更容易理解。它可以用作配置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.json中的所有属性都是用于根据您的需求定制构建任务的,可以随意更改为最喜欢的内容。您可以在VSCode任务文档中了解演示属性(以及其他内容)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接