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

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


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

按照这里的说明,按Ctrl + Shift + P,输入Configure Tasks,选择它并按Enter。

的任务。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就很简单了,比如设置任务。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配置的文件夹。

还有一个CMake集成扩展,它在VScode中添加了一个“CMake build”命令。

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


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

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

此外,您可以在设置中更新配置。如果你想使用不同的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项目,应该可以工作(构建和调试):

vscode-mac-c-example

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

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


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

点击(Ctrl+P)并输入:

ext install cpptools

打开一个文件夹(Ctrl+K & Ctrl+O),并在文件夹中创建一个扩展名为.cpp的新文件(例如:hello.cpp): 输入代码并点击保存。 点击(Ctrl+Shift+P和类型,配置任务运行器,然后选择在列表底部的其他。 在同一个文件夹中创建一个名为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%

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

点击(Ctrl+Shift+B运行构建任务。这将为项目创建.obj和.exe文件。 要调试项目,请按F5并选择c++ (Windows)。 在发射。Json文件,编辑以下行并保存文件:

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

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

你可以在Visual Studio Code的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
}

参考:

C/ c++ VS Code c_cpp_properties。json模板


这里的基本问题是构建和链接c++程序在很大程度上依赖于所使用的构建系统。你将需要支持以下不同的任务,使用一些插件和自定义代码的组合:

General C++ language support for the editor. This is usually done using ms-vscode.cpptools, which most people expect to also handle a lot of other stuff, like build support. Let me save you some time: it doesn't. However, you will probably want it anyway. Build, clean, and rebuild tasks. This is where your choice of build system becomes a huge deal. You will find plugins for things like CMake and Autoconf (god help you), but if you're using something like Meson and Ninja, you are going to have to write some helper scripts, and configure a custom "tasks.json" file to handle these. Microsoft has totally changed everything about that file over the last few versions, right down to what it is supposed to be called and the places (yes, placeS) it can go, to say nothing of completely changing the format. Worse, they've SORT OF kept backward compatibility, to be sure to use the "version" key to specify which variant you want. See details here:

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

...但注意冲突:

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

警告:在下面所有的答案中,任何以“version”标签低于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
                }
            }
        }
    ]
}

Note that, in theory, this file is supposed to work if you put it in the workspace root, so that you aren't stuck checking files in hidden directories (.vscode) into your revision control system. I have yet to see that actually work; test it, but if it fails, put it in .vscode. Either way, the IDE will bitch if it isn't there anyway. (Yes, at the moment, this means I have been forced to check .vscode into subversion, which I'm not happy about.) Note that my build scripts (not shown) simply create (or recreate) a DEBUG directory using, in my case, meson, and build inside it (using, in my case, ninja).

运行、调试、附加、停止。这些是另一组任务,定义在“launch.json”中。至少以前是这样。微软把文档搞得一团糟,我甚至都不确定了。


要在VS代码中构建/运行c++项目,您需要手动配置任务。Json文件,在工作空间文件夹的。vscode文件夹中。 打开任务。json,按ctrl + shift + P,并键入Configure tasks,并按enter,它将带你到tasks.json

在这里,我提供我的任务。json文件,并添加了一些注释,使文件更容易理解,可以作为配置任务的参考。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任务文档中声明

type属性说明:

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

控件可以控制终端的行为 任务中的表示属性。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.


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

Ctrl+,然后设置菜单打开和扩展>运行代码配置向下滚动其属性,并在设置中找到编辑。Json点击它,并添加以下代码在它:

{
 "code-runner.runInTerminal": true
}

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

代码跑 C / c++

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