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

微软的Visual Studio代码编辑器非常不错,但它对构建c++项目没有默认支持。

我如何配置它来做到这一点?

644870 次浏览

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

按照指令在这里,按Ctrl + 转变 + P,键入Configure 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将被执行,错误将在编辑器中下划线显示。

微软现在有一个C/ c++语言扩展。你可以通过“快速打开”(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
}
}
}
]
}

这假设在工作区的根目录中有一个带有CMake配置的文件夹build

还有一个CMake集成扩展,它添加了一个“;CMake build"命令到VScode。

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

有一个更简单的方法来编译和运行c++代码,不需要配置:

  1. 安装代码运行器扩展
  2. 在文本编辑器中打开您的c++代码文件,然后使用快捷方式Ctrl+Alt+N,或按F1然后选择/键入Run Code,或右键单击文本编辑器,然后在上下文菜单中单击Run Code,代码将被编译并运行,输出将显示在输出窗口中。

此外,您可以在设置中更新配置。如果你想使用不同的c++编译器,c++的默认配置如下:

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

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

任务。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"
}

发射。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项目,应该只是工作(构建和调试):

vcode -mac-c-example

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

我计划在Windows和linux上做同样的事情(除非微软先写了像样的文档…)

有了更新的VS Code,你可以用以下方式做到这一点:

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

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

  3. 点击(Ctrl+转变+P并键入,Configure task runner,然后选择列表底部的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+转变+B)运行构建任务。这将为项目创建.obj. exe文件。

  2. 要调试项目,点击F5并选择c++ (Windows)

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

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

一个新的2.0.0任务的makefile任务示例。json版本。

在下面的代码片段中,我希望它们会有用。

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

你可以引用这个最新的要点,有一个版本2.0.0任务的Visual Studio Code, 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. < p > C/ c++ VS Code

  2. < p > c_cpp_properties。json模板

这里的基本问题是构建和链接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以下的标签已经过时。

这是我目前能找到的最接近的东西。请注意,我把大部分繁重的工作都交给了脚本,这并没有给我提供任何我可以接受的菜单项,如果不在这里显式地添加另外三个条目,就没有任何好的方法来选择调试和发布。综上所述,以下是我可以容忍的.vscode/任务。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,这让我很不高兴。)注意,我的构建脚本(没有显示)只是使用(在我的示例中)meson创建(或重新创建)一个DEBUG目录,并在其中构建(在我的示例中使用)ninja。

  1. 运行、调试、附加、停止。这些是另一组任务,定义在“launch.json”中。至少以前是这样。微软把文档搞得一团糟,我甚至都不确定了。
要在VS code中构建/运行c++项目,您需要手动配置工作空间文件夹中的.vscode文件夹中的tasks.json文件。 要打开tasks.json,按ctrl + shift + P,键入配置任务,然后按输入,它将带你到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代码任务文档声明

类型属性的描述:

  • 类型:任务类型。对于自定义任务,这可以是shell或process。如果指定了shell,则对命令进行解释 作为shell命令(例如:bash、cmd或PowerShell)。如果 如果指定了进程,则该命令将被解释为进程到 李执行。< / >

终端的行为可以使用 tasks.json中的>属性。它提供以下属性:

  • 揭示:控制是否将集成终端面板带到前面。有效值为: - 总是 -面板总是带到前面。这是默认值 - 从来没有 -用户必须显式地使用 视图比;终端命令(Ctrl+ ')。 - 沉默 -只有当输出没有扫描错误和警告时,终端面板才会移到前面

  • 焦点:控制终端是否接受输入焦点。默认为false。

  • 回声:控制执行的命令是否在终端中回显。默认为true。

  • showReuseMessage:控制是否显示“终端将被任务重用,按任意键关闭它”;消息。

  • 面板:控制是否在任务运行之间共享终端实例。可能取值为: —共享:共享终端,其他任务运行的输出被添加到同一终端。 —专用的:终端专用于特定的任务。如果该任务再次执行,终端将被重用。然而, 不同任务的输出显示在不同的终端上。 - :该任务的每次执行都使用一个新的干净终端

  • 明确:控制在运行此任务之前是否清除终端。默认为false。

可以使用扩展代码跑运行代码与播放图标在右上角通过快捷键:Ctrl+Alt+N和中止Ctrl+Alt+。但默认情况下,它只显示程序的输出,但对于接收输入,你需要遵循一些步骤:

< kbd > Ctrl < / kbd > + < kbd >, < / kbd >然后打开设置菜单,运行代码配置向下滚动其属性并找到在settings.json中编辑,单击它并在其中添加以下代码:

{
"code-runner.runInTerminal": true
}

首先,去扩展(Ctrl + Shift + X),并安装2个扩展:

  1. 代码跑
  2. C / c++
然后,然后重新加载VS Code并选择一个播放按钮在右上角你的程序在输出终端中运行。你可以通过Ctrl + Alt + N看到输出。 要更改其他功能,请转到用户设置。 enter image description here < / p >