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

275

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

我该如何配置才能实现此功能?


14
在Linux下编译C++代码有很多答案,但在Windows下呢?请提供相关信息。 - Charles Milette
7
这是一些基础的东西,但在Windows中却没有有用的资源来完成它。而且MS CppTools扩展程序也无济于事,不要提那个了,我猜它只会让你更加沮丧。 - Kshitij
有人找到解决方案吗?我能够编译,但无法在VSCode上调试C/C++。这篇文章说只支持在Linux上进行调试。最近我也为此创建了这个线程。感激任何帮助... - Mahesha999
14个回答

177

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

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

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

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

4
我的输出窗口被卡在“正在运行 blablabla”上了,没有提示,什么都没有。我该如何停止代码的运行? - Hichigaya Hachiman
15
停止代码运行,请使用 Ctrl+Alt+M。要使用标准输入读取数据,您可以转到文件->首选项->设置来设置 "code-runner.runInTerminal": true。有关更多详细信息,请参考 https://github.com/formulahendry/vscode-code-runner/issues/91。 - Jun Han
1
在输出窗口运行会阻止终端输入。似乎需要使用runInTerminal... - Andrew Wolfe
现在对于C/C++,这已经可以直接使用了。@SeakyLone,你需要安装并将C++编译器(尝试Mingw)添加到系统环境路径中。(我猜你在Windows上) 如果你在Linux上,请安装G++。 - exilour
30
你应该披露你是正在推广的扩展程序的作者。 - Codebling
显示剩余5条评论

99

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

按照这里的说明,按下 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 将被执行,并且编辑器中的错误将被下划线标出。

18
警告 - 此文件的格式已更改,原文不再正确。请参见: https://go.microsoft.com/fwlink/?LinkId=733558 - breakpoint
默认的构建任务快捷键是 ctrl+alt+b - Melroy van den Berg
1
有没有一个命令或绑定可以在终端中跳转到下一个/上一个错误?我遇到了这样的情况,因为VS Code不知道如何构建我的项目(教它太过繁琐),所以“问题”窗格中有许多无关紧要的问题,但是在构建后,“终端”中充满了有用的错误。我只需要一个键盘快捷键来跳转到“终端”中的下一个错误... - Dan L

57

一个适用于新的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
                }
            }
        }
    ]
}

2
截至2018年11月依然是最新的。谢谢! - TheIntern
你把它放在哪个目录下了?根目录、".vs" 或 ".vscode"?理论上,如果文件也要进入版本控制(我强烈建议这样做),工作区根目录是唯一推荐的位置,但我无法让它正常工作。 - breakpoint
据我所知,目前唯一有效的位置是.vscode。对于Git版本控制,一种可能性是在.gitignore中使用模式,如!.vscode/tasks.json - attdona

17

以下是我如何为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. Visual Studio Code 的 C/C++ 扩展

  2. c_cpp_properties.json 模板


17
也许您也想简要解释一下您的设置是如何工作的,而不仅仅是复制粘贴内容。请注意,翻译后的内容不包括任何解释或额外信息。 - uitty400
2
我很难解释我的设置。 - Li Kui
请确保将路径更改为您安装MinGW的位置。 - Anthony Lei
你也可以使用/**递归地包含子文件夹,而不是在"C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/7.2.0/include"中重复各个子文件夹。 - questionto42

16
要在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任务文档

type属性的描述:

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

通过在tasks.json中使用presentation属性可以控制终端的行为, 它提供以下属性:

  • reveal: 控制是否将集成终端面板置于前台。有效值为: - always - 面板始终置于前台。这是默认值。 - never - 用户必须显式使用查看>终端命令(Ctrl+`)将终端面板置于前台。 - silent - 仅当输出未被扫描以查找错误和警告时,终端面板才会置于前台。

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

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

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

  • panel: 控制终端实例是否在任务运行之间共享。可能的值为: - shared: 终端是共享的,其他任务运行的输出添加到同一个终端中。 - dedicated: 终端专用于特定任务。如果再次执行该任务,则会重复使用该终端。但是,不同任务的输出会呈现在不同的终端中。 - new: 每次执行该任务都使用新的干净终端。

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


11

首先,进入扩展程序(Ctrl + Shift + X)并安装两个扩展程序:

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

然后,重新加载VS Code,并在右上角选择播放按钮,您的程序将在输出终端中运行。 您可以通过 Ctrl + Alt + N 查看输出结果。 要更改其他功能,请前往用户设置。 enter image description here


这是之前答案的重复。 - JDługosz

11

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

vscode-mac-c-example

请注意,它需要XCode和VSCode Microsoft C++工具扩展。

我计划为Windows和Linux做同样的事情(除非Microsoft先撰写出优秀的文档......)。


7
这里的基本问题在于构建和链接C++程序严重依赖于使用的构建系统。您需要使用一些插件和自定义代码来支持以下不同的任务:
1. 编辑器的通用C++语言支持。通常使用ms-vscode.cpptools完成,大多数人期望它也处理很多其他东西,比如构建支持。让我为您节省一些时间:它不会。但是,您可能仍然想要它。
2. 构建、清理和重新构建任务。这就是您选择构建系统变得非常重要的地方。您会发现一些针对CMake和Autoconf(上帝保佑你)之类的插件,但如果您使用的是像Meson和Ninja这样的东西,您将不得不编写一些辅助脚本,并配置一个自定义的"tasks.json"文件来处理这些任务。微软在过去几个版本中完全改变了该文件的所有内容,甚至包括它应该被称为什么以及它可以放置的位置(是的,位置S),更不用说完全改变了格式。更糟糕的是,他们已经部分保持了向后兼容性,因此请务必使用"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 加入到子版本控制系统中,我对此并不满意。)请注意,我的构建脚本(未显示)只是使用 meson 在 DEBUG 目录下创建(或重新创建)一个目录,并在其中构建(在我的情况下使用 ninja)。
3. 运行、调试、附加、暂停。这些是另一组任务,在 "launch.json" 中定义。至少它们曾经是。微软已经把文档搞得一团糟,我甚至不确定了。

这是一个示例,build-scripts/build-debug.sh文件。理想情况下,这些将继承构建上下文(调试、发布、分析等),但我无法弄清楚Code如何管理它,即使它有这个概念。请原谅格式;加油,StackOverflow!#!/bin/bash if [ ! -d "DEBUG" ]; then mkdir DEBUG meson DEBUG ficd DEBUG ninja if [ $? -eq 0 ]; then exit 0 else exit $? fi - breakpoint
哦,再次提醒:在完成这些步骤后,请按下CTRL-SHIFT-B来调出构建任务。我真的非常希望有一个包含所有这些功能的正确主菜单,但我还没有想出如何实现它。 - breakpoint

6

以下是我使用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'扩展


我能够在VSCode上编译C/C++代码,但无法进行调试。这篇文章指出只有在Linux系统上才支持调试功能。最近我也发起了这个帖子,希望能得到帮助...非常感谢! - Mahesha999

5

使用更新的VS Code,您可以按照以下方式完成操作:

  1. 按下 (Ctrl+P),然后输入:
ext install cpptools
  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%
  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 并选择C++(Windows)

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

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

按下 F5 键。

1
我正在使用最新的VSC。第4步让我有点摸不着头脑。配置任务运行器不可用。 - Louis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接