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

问题描述 投票:167回答:12

微软的Visual Studio Code编辑器相当不错,但它没有构建C ++项目的默认支持。

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

visual-studio-code vscode-tasks
12个回答
104
投票

有一种更简单的方法来编译和运行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"
}

2
投票

你可以参考这个最新的要点有一个版本2.0.0任务Visual Studio Code,https://gist.github.com/akanshgulati/56b4d469523ec0acd9f6f59918a9e454

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


2
投票

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

  1. 对编辑器的常规C ++语言支持。这通常使用ms-vscode.cpptools来完成,大多数人都希望它还可以处理很多其他内容,比如构建支持。让我省你一些时间:它没有。但是,无论如何,你可能会想要它。
  2. 构建,清理和重建任务。这是您选择构建系统变得非常重要的地方。你会找到像CMake和Autoconf(上帝帮助你)的插件,但是如果你使用像Meson和Ninja这样的东西,你将不得不编写一些帮助脚本,并配置一个自定义的“tasks.json”文件到处理这些。微软在最后几个版本中完全改变了该文件的所有内容,直到它应该被调用的内容和它可以去的地方(是的,placeS),更不用说完全改变格式了。更糟糕的是,他们的SORT OF保持向后兼容性,以确保使用“version”键来指定您想要的变体。详情请见:

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

}

请注意,理论上,如果将此文件放在工作空间根目录中,则该文件应该可以正常工作,这样您就不会将隐藏目录(.vscode)中的文件检查到修订控制系统中。我还没有看到实际工作;测试它,但如果失败,请将其放入.vscode。无论哪种方式,如果它不存在,IDE将会婊子。 (是的,目前,这意味着我被迫检查.vscode到subversion,我不满意。)请注意,我的构建脚本(未显示)只是使用,创建(或重新创建)DEBUG目录我的情况,介子和内部构建(在我的例子中,使用忍者)。

  1. 运行,调试,附加,暂停。这些是另一组任务,在“launch.json”中定义。或者至少他们曾经是。微软已经制作了这样的文档哈希,我甚至不再确定了。

2
投票

要在VS代码中构建/运行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:任务的类型。对于自定义任务,这可以是shell或进程。如果指定了shell,则该命令将被解释为shell命令(例如:bash,cmd或PowerShell)。如果指定了process,则该命令将被解释为要执行的进程。

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

  • 揭示:控制集成终端面板是否被带到前面。有效值为: 总是 - 面板总是被带到前面。这是默认值 never - 用户必须使用View> Terminal命令(Ctrl +`)明确地将终端面板置于前面。 静音 - 仅在未扫描输出错误和警告时才将终端面板置于前面。
  • focus:控制终端是否正在进行输入焦点。默认值为false。
  • echo:控制执行的命令是否在终端中回显。默认为true。
  • showReuseMessage:控制是否显示“终端将被任务重用,按任意键关闭它”消息。
  • panel:控制是否在任务运行之间共享终端实例。可能的值是: shared:终端被共享,其他任务运行的输出被添加到同一终端。 专用:终端专用于特定任务。如果再次执行该任务,则重新使用终端。但是,不同任务的输出在不同的终端中呈现。 new:该任务的每次执行都使用一个新的干净终端。
  • clear:控制在运行此任务之前是否清除终端。默认值为false。

77
投票

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

按照here说明操作,按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
                }
            }
        }
    ]
}

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

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

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


37
投票

新的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
                }
            }
        }
    ]
}

9
投票

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

确保将适当的路径更改为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

8
投票

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

vscode-mac-c-example

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

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


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为VScode添加了“CMake build”命令。

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


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

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”扩展


4
投票

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

  1. 点击(Ctrl + P)并输入: ext install cpptools
  2. 打开文件夹(Ctrl + K和Ctrl + O)并在扩展名为.cpp(例如:hello.cpp)的文件夹中创建一个新文件:
  3. 输入您的代码并点击保存。
  4. 点击(Ctrl + Shift + P并键入,Configure task runner,然后在列表底部选择other
  5. 在名为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%
  6. 编辑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" }
  7. 点击(Ctrl + Shift + B运行构建任务。这将为项目创建.obj和.exe文件。
  8. 要调试项目,请按F5并选择C ++(Windows)。
  9. 在launch.json文件中,编辑以下行并保存文件: "program": "${workspaceRoot}/hello.exe",
  10. 点击F5。

3
投票

现在有一个来自Microsoft的C / C ++语言扩展。您可以通过转到“快速打开”(Ctrl + p)并键入以下内容来安装它:

ext install cpptools

你可以在这里读到它:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.