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

193 visual-studio-code vscode-tasks

Microsoft的Visual Studio代码编辑器相当不错,但它没有构建C++项目的默认支持.

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

Jun*_*Han 113

有一种更简单的方法来编译和运行C++代码,无需配置:

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

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

"code-runner.executorMap": {
    "cpp": "g++ $fullFileName && ./a.out"
}
Run Code Online (Sandbox Code Playgroud)

  • 您应该透露您是所推广的扩展程序的作者。 (17认同)
  • 要停止代码运行,请使用"Ctrl + Alt + M".要使用stdin读取数据,可以转到`File`->`Preference`->`Settings`来设置``code-runner.runInTerminal":true`.有关详细信息,请参阅https://github.com/formulahendry/vscode-code-runner/issues/91 (8认同)
  • 我的输出窗口停留在`运行blablabla`.没有提示,没有.我怎么能阻止代码运行? (3认同)

小智 80

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

按照此处的说明操作,按Ctrl+ Shift+ P,键入Configure Tasks,选择它并按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
                }
            }
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

现在转到菜单文件首选项键盘快捷键,并为构建任务添加以下键绑定:

// Place your key bindings in this file to overwrite the defaults
[
    { "key": "f8",          "command": "workbench.action.tasks.build" }
]
Run Code Online (Sandbox Code Playgroud)

现在当您按下F8Makefile时将执行,并且编辑器中的错误将加下划线.

  • 警告-此文件的格式已更改,这不再正确。请参阅:https://go.microsoft.com/fwlink/?LinkId=733558 (3认同)

att*_*ona 40

新的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
                }
            }
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

  • 2018 年 11 月仍然是最新的。谢谢! (2认同)

Li *_*Kui 10

这是我如何配置我的VS for C++

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++"??                  
           }
   ]
}
Run Code Online (Sandbox Code Playgroud)

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

参考:

  1. 用于VS代码的C/C++

  2. c_cpp_properties.json模板

  • 也许你还想解释一下你的设置是做什么的,而不仅仅是复制粘贴的东西 (7认同)
  • 我很难解释我的设置。 (2认同)

小智 9

出于对缺乏清晰文档的沮丧,我在github上创建了一个应该正常工作的Mac项目(包括构建和调试):

vscode-MAC-C-示例

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

我打算为Windows和Linux做同样的事情(除非微软首先写出体面的文档......).


小智 9

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

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

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


jok*_*007 7

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

在这里,我为我的task.json文件提供一些注释,以使该文件更易于理解,它可以用作配置task.json的参考,我希望它会有用

task.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"
        },

    ]
}
Run Code Online (Sandbox Code Playgroud)

现在,直接从VS代码任务文档中进行说明

类型属性的描述:

  • type:任务的类型。对于自定义任务,这可以是shell或进程。如果指定了shell,则该命令将解释为shell命令(例如:bash,cmd或PowerShell)。如果指定了process,则该命令将被解释为要执行的过程。

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

  • 显示:控制是否将集成终端面板置于前面。有效值为:

    • 始终 -面板总是放在最前面。这是默认值
    • 从不 -用户必须使用“视图”>“终端”命令(Ctrl +`)将终端面板显式显示在最前面。
    • 无声 -仅在不扫描输出中是否有错误和警告的情况下,才将终端面板置于前面。
  • focus:控制终端是否获取输入焦点。默认为false。

  • echo:控制是否在终端中回显执行的命令。默认为true。
  • showReuseMessage:控制是否显示“终端将被任务重用,按任意键将其关闭”消息。
  • panel:控制是否在任务运行之间共享终端实例。可能的值为:
    • shared共享终端,并将其他任务运行的输出添加到同一终端。
    • 专用:终端专用于特定任务。如果再次执行该任务,则将重新使用终端。但是,不同任务的输出将显示在不同终端中。
    • new:该任务的每次执行都使用新的干净终端。
  • clear:控制是否在运行此任务之前清除终端。默认为false。


lar*_*moa 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
                }
            }
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

这假设build工作空间的根目录中有一个具有CMake配置的文件夹.

还有一个CMake集成扩展,它为VScode添加了一个"CMake build"命令.

PS!该problemMatcher是设置为clang-builds.要使用GCC,我相信您需要更改fileLocationrelative,但我没有测试过这一点.


Vla*_*den 5

以下是我使用g ++编译器配置VS for C++的方法,它的工作原理很好,包括调试选项:

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"
}
Run Code Online (Sandbox Code Playgroud)

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"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

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


小智 5

使用更新的 VS Code,您可以通过以下方式执行此操作:

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

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

  3. 点击 ( Ctrl+ Shift+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%
Run Code Online (Sandbox Code Playgroud)
  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"
}
Run Code Online (Sandbox Code Playgroud)
  1. 点击 ( ++Ctrl运行构建任务。这将为项目创建.objShift.exe文件。B

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

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

"program": "${workspaceRoot}/hello.exe",
Run Code Online (Sandbox Code Playgroud)
  1. F5


bre*_*int 5

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

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

  2. 生成,清理和重建任务。这是您选择构建系统的地方。您会找到CMake和Autoconf之类的插件(上帝会帮助您),但是如果您使用的是Meson和Ninja之类的插件,则必须编写一些帮助程序脚本,并配置一个自定义的“ tasks.json”文件以处理这些。在最近的几个版本中,Microsoft完全更改了该文件的所有内容,直到应有的名称以及可以使用的位置(是,placeS),更不用说完全更改格式了。更糟糕的是,它们的SORT OF保持了向后兼容性,以确保使用“版本”键来指定所需的变体。在这里查看详细信息:

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

...但请注意与以下内容冲突:

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

警告:在下面的所有答案中,低于2.0.0的带有“版本”标签的所有内容均不适用。

这是我目前最接近的东西。请注意,我将大部分繁重的工作放在脚本上,这实际上并没有给我提供我可以使用的任何菜单条目,并且没有任何好的方法可以在调试和发布之间进行选择,而不仅仅是在其中添加三个显式条目。这里。话虽如此,这是我目前可以容忍的.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
            }
        }
    }
]
Run Code Online (Sandbox Code Playgroud)

}

请注意,从理论上讲,如果将该文件放在工作区根目录中,则该文件应该可以工作,这样就不会卡住隐藏目录(.vscode)中的文件到修订控制系统中。我还没有看到它真正起作用。测试它,但如果失败,则将其放入.vscode。无论哪种方式,如果IDE仍然不存在,IDE都会bit之以鼻。(是的,目前,这意味着我不得不将.vscode签入Subversion,对此我感到不满意。)请注意,我的构建脚本(未显示)仅使用以下命令创建(或重新创建)DEBUG目录:我的情况,介子,并在其中建立(在我的情况下,使用忍者)。

  1. 运行,调试,附加,停止。这些是另一组任务,在“ launch.json”中定义。或者至少他们曾经是。微软对文档进行了这样的哈希处理,我什至不确定。