如何设置Visual Studio Code来编译C++代码?

How do I set up Visual Studio Code to compile C++ code?

Microsoft 的 Visual Studio Code 编辑器非常好,但它没有默认支持构建 C++ 项目。

如何配置它来执行此操作?

构建任务是特定于项目的。要创建新项目,请在 Visual Studio 代码中打开一个目录。

按照说明here,按Ctrl + Shift + P , 输入 Configure Tasks, select 然后按 Enter.

tasks.json 文件将被打开。将以下构建脚本粘贴到文件中并保存:

{
    "version": "0.1.0",
    "command": "make",
    "isShellCommand": true,
    "tasks": [
        {
            "taskName": "Makefile",

            // Make this the default build command.
            "isBuildCommand": true,

            // Show the output window only if unrecognized errors occur.
            "showOutput": "always",

            // Pass 'all' as the build target
            "args": ["all"],

            // Use the standard less compilation problem matcher.
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": ["relative", "${workspaceRoot}"],
                "pattern": {
                    "regexp": "^(.*):(\d+):(\d+):\s+(warning|error):\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        }
    ]
}

现在转到菜单文件首选项键盘快捷键,然后添加以下内容构建任务的键绑定:

// Place your key bindings in this file to overwrite the defaults
[
    { "key": "f8",          "command": "workbench.action.tasks.build" }
]

现在当您按下 F8 时,Makefile 将被执行,错误将在编辑器中加下划线。

现在有来自 Microsoft 的 C/C++ 语言扩展。您可以通过转到 "quick open" 东西 (Ctrl+p) 并键入:

来安装它
ext install cpptools

您可以在这里阅读:

https://blogs.msdn.microsoft.com/vcblog/2016/03/31/cc-extension-for-visual-studio-code/

这是非常基本的,截至 2016 年 5 月。

如果您的项目具有 CMake 配置,则可以非常直接地进行设置 VSCode,例如像下面这样设置 tasks.json

{
    "version": "0.1.0",
    "command": "sh",
    "isShellCommand": true,
    "args": ["-c"],
    "showOutput": "always",
    "suppressTaskName": true,
    "options": {
        "cwd": "${workspaceRoot}/build"
    },
    "tasks": [
        {
            "taskName": "cmake",
            "args": ["cmake ."]
        },
        {
            "taskName": "make",
            "args" : ["make"],
            "isBuildCommand": true,
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": "absolute",
                "pattern": {
                    "regexp": "^(.*):(\d+):(\d+):\s+(warning|error):\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        }
    ]
}

这里假定工作区的根目录中有一个文件夹 build,其中包含 CMake 配置。

还有一个 CMake integration extension 将“CMake 构建”命令添加到 VScode。

PS! problemMatcher 是为 clang-builds 设置的。要使用 GCC,我相信您需要将 fileLocation 更改为 relative,但我还没有对此进行测试。

编译和 运行 C++ 代码更简单,无需配置:

  1. 安装 Code Runner Extension
  2. 在文本编辑器中打开您的 C++ 代码文件,然后使用快捷键 Ctrl+Alt+N,或按 F1,然后按 select/type Run Code,或右键单击文本编辑器并然后在上下文菜单中单击Run Code,代码将被编译并运行,输出将显示在Output Window.

此外,您可以根据需要使用不同的 C++ 编译器更新 settings.json 中的配置,C++ 的默认配置如下:

"code-runner.executorMap": {
    "cpp": "g++ $fullFileName && ./a.out"
}

下面是我如何使用 g++ 编译器为 C++ 配置我的 VS,它工作得很好,包括调试选项:

tasks.json 文件

{
    "version": "0.1.0",
    "command": "g++",
    "isShellCommand": true,
    // compiles and links with debugger information
    "args": ["-g", "-o", "hello.exe", "hello.cpp"],
    // without debugger information
    // "args": ["-o", "hello.exe", "hello.cpp"],
    "showOutput": "always"
}

launch.json 文件

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "C++ Launch (Windows)",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceRoot}/hello.exe",
            "MIMode": "gdb",
            "miDebuggerPath": "C:\MinGw\bin\gdb.exe",
            "stopAtEntry": false,
            "cwd": "${workspaceRoot}",
            "externalConsole": false,
            "visualizerFile": "${workspaceRoot}/my.natvis"
        }
    ]
}

我还在 VS Code 中安装了 'C/C++ for Visual Studio Code' 扩展程序

由于缺乏清晰的文档而感到沮丧, 我在 github 上创建了一个 Mac 项目,应该可以正常工作(构建和调试):

vscode-mac-c-example

请注意,它需要 XCode 和 VSCode Microsoft cpptools 扩展。

我计划对 Windows 和 linux 做同样的事情(除非微软先写出像样的文档...)。

使用更新后的 VS 代码,您可以按以下方式进行操作:

  1. 点击 (Ctrl+P) 并输入:
ext install cpptools
  1. 打开文件夹 (Ctrl+K & Ctrl+ O) 并在文件夹内创建一个扩展名为 .cpp 的新文件(例如:hello.cpp):

  2. 输入您的代码并点击保存。

  3. 点击 (Ctrl+Shift+P 并输入, Configure task runner 然后是列表底部的 select other

  4. 在同一文件夹中创建一个名为 build.bat 的批处理文件,并在文件正文中包含以下代码:

@echo off
call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x64     
set compilerflags=/Od /Zi /EHsc
set linkerflags=/OUT:hello.exe
cl.exe %compilerflags% hello.cpp /link %linkerflags%
  1. 按如下方式编辑task.json文件并保存:
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "build.bat",
    "isShellCommand": true,
    //"args": ["Hello World"],
    "showOutput": "always"
}
  1. 按(Ctrl+Shift+B到运行 构建任务。这将为项目创建 .obj.exe 文件。

  2. 调试项目,点击F5和select C++(Windows).

  3. launch.json文件中,编辑以下行并保存文件:

"program": "${workspaceRoot}/hello.exe",
  1. 点击F5

新 2.0.0 tasks.json 版本的 makefile 任务示例。

下面的代码片段中有一些评论,希望它们有用。

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "<TASK_NAME>",
            "type": "shell",
            "command": "make",
            // use options.cwd property if the Makefile is not in the project root ${workspaceRoot} dir
            "options": {
                "cwd": "${workspaceRoot}/<DIR_WITH_MAKEFILE>"
            },
            // start the build without prompting for task selection, use "group": "build" otherwise
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                "echo": true,
                "reveal": "always",
                "focus": false,
                "panel": "shared"
            },
            // arg passing example: in this case is executed make QUIET=0
            "args": ["QUIET=0"],
            // Use the standard less compilation problem matcher.
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": ["absolute"],
                "pattern": {
                    "regexp": "^(.*):(\d+):(\d+):\s+(warning|error):\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        }
    ]
}

您可以参考这个最新的要点,它具有 Visual Studio 代码的 2.0.0 版本任务,https://gist.github.com/akanshgulati/56b4d469523ec0acd9f6f59918a9e454

您可以轻松地编译和 运行 每个文件而无需更新任务。它是通用的,还可以打开输入条目的终端。

这是我为 C++ 配置 VS 的方式

确保将适当的路径更改为安装 MinGW 的位置

launch.json

{
   "version": "0.2.0",
   "configurations": [
       {
           "name": "C++ Launch (GDB)",                
           "type": "cppdbg",                         
           "request": "launch",                        
           "targetArchitecture": "x86",                
           "program": "${workspaceRoot}\${fileBasename}.exe",                 
           "miDebuggerPath":"C:\mingw-w64\bin\gdb.exe", 
           "args": [],     
           "stopAtEntry": false,                  
           "cwd": "${workspaceRoot}",                  
           "externalConsole": true,                  
           "preLaunchTask": "g++"                    
           }
   ]
}

tasks.json


{
    "version": "0.1.0",
    "command": "g++",
    "args": ["-g","-std=c++11","${file}","-o","${workspaceRoot}\${fileBasename}.exe"],
    "problemMatcher": {
        "owner": "cpp",
        "fileLocation": ["relative", "${workspaceRoot}"],
        "pattern": {
            "regexp": "^(.*):(\d+):(\d+):\s+(warning|error):\s+(.*)$",
            "file": 1,
            "line": 2,
            "column": 3,
            "severity": 4,
            "message": 5
        }
    }
}

c_cpp_properties.json

{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceRoot}",
                "C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++",
                "C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/x86_64-w64-mingw32",
                "C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/backward",
                "C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include",
                "C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/tr1",
                "C:/mingw-w64/x86_64-w64-mingw32/include"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "__GNUC__=6",
                "__cdecl=__attribute__((__cdecl__))"
            ],
            "intelliSenseMode": "msvc-x64",
            "browse": {
                "path": [
                    "${workspaceRoot}",
                    "C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++",
                    "C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/x86_64-w64-mingw32",
                    "C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/backward",
                    "C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include",
                    "C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include/c++/tr1",
                    "C:/mingw-w64/x86_64-w64-mingw32/include"
                ]
            },
            "limitSymbolsToIncludedHeaders": true,
            "databaseFilename": ""
        }
    ],
    "version": 3
}

参考:

  1. C/C++ for VS Code

  2. c_cpp_properties.json template

这里的基本问题是构建和链接 C++ 程序在很大程度上取决于所使用的构建系统。您将需要使用插件和自定义代码的某种组合来支持以下不同的任务:

  1. 编辑器的一般 C++ 语言支持。这通常是使用 ms-vscode.cpptools 完成的,大多数人希望它也能处理很多其他的东西,比如构建支持。让我为您节省一些时间:事实并非如此。但是,您可能还是想要它。

  2. 构建、清理和重建任务。这是您选择构建系统变得非常重要的地方。你会找到 CMake 和 Autoconf 之类的插件(上帝保佑你),但是如果你使用的是 Meson 和 Ninja 之类的东西,你将不得不编写一些帮助脚本,并配置一个自定义的“tasks.json”文件来处理这些。在过去的几个版本中,微软已经完全改变了该文件的所有内容,包括它应该被调用的名称和它可以去的地方(是的,placeS),更不用说完全改变格式了。更糟糕的是,他们有点保持向后兼容性,以确保使用“版本”键来指定您想要的变体。在此处查看详细信息:

https://code.visualstudio.com/docs/editor/tasks

...但注意冲突:

https://code.visualstudio.com/docs/languages/cpp

警告:在下面的所有答案中,任何以“版本”标签开头的低于 2.0.0 的内容均已过时。

这是我目前得到的最接近的东西。请注意,我把大部分繁重的工作都交给了脚本,这实际上并没有给我任何我可以接受的菜单条目,而且没有任何好的方法可以在调试和发布之间 select 而不是只做另一个这里有三个显式条目。综上所述,这是我目前可以容忍的 .vscode/tasks.json 文件:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build project",
            "type": "shell",
            "command": "buildscripts/build-debug.sh",
            "args": [],

            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                // Reveal the output only if unrecognized errors occur.
                "echo": true,
                "focus": false,
                "reveal": "always",
                "panel": "shared"
            },

            // Use the standard MS compiler pattern to detect errors, warnings and infos
            "options": {
                "cwd": "${workspaceRoot}"
            },
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": ["relative", "${workspaceRoot}/DEBUG"],
                "pattern": {
                    "regexp": "^(.*):(\d+):(\d+):\s+(warning|error):\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        },
        {
            "label": "rebuild project",
            "type": "shell",
            "command": "buildscripts/rebuild-debug.sh",
            "args": [],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                // Reveal the output only if unrecognized errors occur.
                "echo": true,
                "focus": false,
                "reveal": "always",
                "panel": "shared"
            },

            // Use the standard MS compiler pattern to detect errors, warnings and infos
            "options": {
                "cwd": "${workspaceRoot}"
            },
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": ["relative", "${workspaceRoot}/DEBUG"],
                "pattern": {
                    "regexp": "^(.*):(\d+):(\d+):\s+(warning|error):\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        },
        {
            "label": "clean project",
            "type": "shell",
            "command": "buildscripts/clean-debug.sh",
            "args": [],

            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                // Reveal the output only if unrecognized errors occur.
                "echo": true,
                "focus": false,
                "reveal": "always",
                "panel": "shared"
            },

            // Use the standard MS compiler pattern to detect errors, warnings and infos
            "options": {
                "cwd": "${workspaceRoot}"
            },
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": ["relative", "${workspaceRoot}/DEBUG"],
                "pattern": {
                    "regexp": "^(.*):(\d+):(\d+):\s+(warning|error):\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        }
    ]
}

请注意,理论上,如果您将此文件放在工作区根目录中,它应该可以工作,这样您就不会卡在将隐藏目录 (.vscode) 中的文件检查到修订控制中系统。我还没有看到它真的有效;对其进行测试,但如果失败,则将其放入 .vscode。无论哪种方式,如果 IDE 不存在,它就会发牢骚。 (是的,目前,这意味着我被迫将 .vscode 检查到 subversion 中,我对此并不满意。)请注意,我的构建脚本(未显示)只是创建(或重新创建)一个 DEBUG在我的例子中使用介子的目录,并在其中构建(在我的例子中使用忍者)。

  1. 运行、调试、附加、停止。这些是另一组任务,定义在“launch.json”中。或者至少他们曾经是。微软把文档搞得这么乱,我都不敢确定了。

对于Build/run VS code中的C++项目,您需要手动配置tasks.json文件,该文件位于.vscode 工作区文件夹中的文件夹。 要打开 tasks.json ,请按 ctrl + shift + P ,然后输入 Configure tasks ,然后按 enter,它将带您到 tasks.json

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

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}\build\${fileBasenameNoExtension}",    //output file name
                "&&",   //to join building and running of the file
                "${workspaceFolder}\build\${fileBasenameNoExtension}"
            ],
            "group": {
                "kind": "build",    //defines to which group the task belongs
                "isDefault": true
            },
            "presentation": {   //Explained in detail below
                "echo": false,
                "reveal": "always",
                "focus": true,
                "panel": "shared",
                "clear": false,
                "showReuseMessage": false
            },
            "problemMatcher": "$gcc"
        },
        
    ]
}

现在,直接从 VS code tasks documentation

类型的描述 属性 :

  • type: The task's type. For a custom task, this can either be shell or process. If shell is specified, the command is interpreted as a shell command (for example: bash, cmd, or PowerShell). If process is specified, the command is interpreted as a process to execute.

终端的行为可以使用 演示文稿 属性 在 tasks.json 中。它提供以下属性:

  • reveal: Controls whether the Integrated Terminal panel is brought to front. Valid values are: - always - The panel is always brought to front. This is the default - never - The user must explicitly bring the terminal panel to the front using the View > Terminal command (Ctrl+`). - silent - The terminal panel is brought to front only if the output is not scanned for errors and warnings.

  • focus: Controls whether the terminal is taking input focus or not. Default is false.

  • echo: Controls whether the executed command is echoed in the terminal. Default is true.

  • showReuseMessage: Controls whether to show the "Terminal will be reused by tasks, press any key to close it" message.

  • panel: Controls whether the terminal instance is shared between task runs. Possible values are: - shared: The terminal is shared and the output of other task runs are added to the same terminal. - dedicated: The terminal is dedicated to a specific task. If that task is executed again, the terminal is reused. However, the output of a different task is presented in a different terminal. - new: Every execution of that task is using a new clean terminal.

  • clear: Controls whether the terminal is cleared before this task is run. Default is false.

可以使用扩展 Code Runner 到 运行 代码,播放图标在顶部 按快捷键右键 ans :Ctrl+ Alt+N 并中止 Ctrl+Alt+ M。但默认情况下它只显示程序的输出但要接收输入你需要遵循一些步骤:

Ctrl+, and then settings menu opens and Extensions>Run Code Configuration scroll down its attributes and find Edit in settings.json click on it and add following code insite it :

{
 "code-runner.runInTerminal": true
}

首先,转到扩展程序 (Ctrl + Shift + X) 并安装 2 个扩展程序:

  1. 代码运行器
  2. C/C++

然后,然后重新加载 VS Code 和 select 右上角的播放按钮,您的程序将在输出终端中运行。您可以通过 Ctrl + Alt + N 查看输出。 要更改其他功能,请转到用户设置。