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

发布于 2025-02-07 14:30:58 字数 162 浏览 3 评论 0 原文

Microsoft的 Visual Studio Code 编辑器非常好,但是对构建C ++项目没有默认支持。

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

Microsoft's Visual Studio Code editor is quite nice, but it has no default support for building C++ projects.

How do I configure it to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

も星光 2025-02-14 14:30:59

您可以参考具有版本 2.0.0 的最新要点, https://gist.github.com/akanshgulati/56B4D469523EC0ACD9F6F59918A9E454

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

You can reference to this latest gist having a version 2.0.0 task for Visual Studio Code, https://gist.github.com/akanshgulati/56b4d469523ec0acd9f6f59918a9e454

You can easily compile and run each file without updating the task. It's generic and also opens the terminal for input entries.

唱一曲作罢 2025-02-14 14:30:59

现在有来自Microsoft的C/C ++语言扩展。您可以通过转到“快速打开”的东西( ctrl + p )和键入:

ext install cpptools

您可以在此处阅读:

非常基本。

There's now a C/C++ language extension from Microsoft. You can install it by going to the "quick open" thing (Ctrl+p) and typing:

ext install cpptools

You can read about it here:

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

It's very basic, as of May 2016.

脱离于你 2025-02-14 14:30:58

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

按照说明在这里,按 ctrl> ctrl + shift + p ,类型配置任务,选择它,然后按 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
                }
            }
        }
    ]
}

现在转到菜单 file 首选项键盘快捷键,然后添加以下键绑定构建任务:

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

现在,当您按 f8 时,将执行makefile,并且编辑器将在编辑器中强调错误。

The build tasks are project specific. To create a new project, open a directory in Visual Studio Code.

Following the instructions here, press Ctrl + Shift + P, type Configure Tasks, select it and press Enter.

The tasks.json file will be opened. Paste the following build script into the file, and save it:

{
    "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+(.*)
quot;,
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        }
    ]
}

Now go to menu FilePreferencesKeyboard Shortcuts, and add the following key binding for the build task:

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

Now when you press F8 the Makefile will be executed, and errors will be underlined in the editor.

涫野音 2025-02-14 14:30:58

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

A makefile task example for new 2.0.0 tasks.json version.

In the snippet below some comments I hope they will be useful.

{
    "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+(.*)
quot;,
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        }
    ]
}
半山落雨半山空 2025-02-14 14:30:58

这是我为C ++配置VS的方式,

请确保将适当的路径更改为安装MINGW

启动的

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

位置 。


{
    "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 ++ vs代码


Here is how I configured my VS for C++

Make sure to change appropriete paths to where your MinGW installed

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+(.*)
quot;,
            "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
}

Reference:

  1. C/C++ for VS Code

  2. c_cpp_properties.json template

反话 2025-02-14 14:30:58

要在VS代码中构建/运行C ++项目,您需要手动配置 tasks.json 文件,该文件位于Workspace文件夹中的 .vscode 文件夹中。
打开 tasks.json ,按 ctrl + shift + p ,然后type 配置任务,然后按 enter 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代码任务文档

类型的描述属性:

  • 类型:任务类型。对于自定义任务,可以是外壳或进程。如果指定了外壳,则解释命令
    作为外壳命令(例如:bash,cmd或powershell)。如果
    指定了过程,该命令被解释为
    执行。

可以使用
演示 tasks.json 中的属性。它提供以下属性:

  • 揭示:控制集成的终端面板是否被带到前面。有效值为:
    - 始终 - 面板始终将面板放在前面。这是默认
    - 从不
    查看&gt;终端命令(ctrl+`)。
    - 无声 - 仅在未扫描输出以显示错误和警告时,终端面板才会前面。


  • 焦点:控制终端是否采取输入焦点。默认值为false。

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

  • showreusemessage :控制是否显示“终端将由任务重复使用,请按任何键关闭它”消息。

  • 面板:控制任务运行之间的终端实例是否共享。可能的值是:
    - 共享:共享终端,并将其他任务运行的输出添加到同一终端。
    - 专用:终端专用于特定任务。如果该任务再次执行,则将重复使用终端。但是,
    不同任务的输出以不同的终端表示。
    - new :该任务的每个执行都使用新的干净终端。

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


To Build/run C++ projects in VS code , you manually need to configure tasks.json file which is in .vscode folder in workspace folder .
To open tasks.json , press ctrl + shift + P , and type Configure tasks , and press enter, it will take you to tasks.json

Here i am providing my tasks.json file with some comments to make the file more understandable , It can be used as a reference for configuring tasks.json , i hope it will be useful

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

Now , stating directly from the VS code tasks documentation

description of type property :

  • type: The task's type. For a custom task, this can either be shell or process. If shell is specified, the command is interpreted
    as a shell command (for example: bash, cmd, or PowerShell). If
    process is specified, the command is interpreted as a process to
    execute.

The behavior of the terminal can be controlled using the
presentation property in tasks.json . It offers the following properties:

  • 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.

梦里南柯 2025-02-14 14:30:58

由于缺乏明确的文件而感到沮丧,
我已经在GitHub上创建了一个Mac项目,该项目应该只能使用(构建和调试):

vscode -MAC-C-示例

请注意,它需要Xcode和Vscode Microsoft Cpptools扩展名。

我计划在Windows和Linux上执行相同的操作(除非Microsoft首先编写体面的文档...)。

Out of frustration at the lack of clear documentation,
I've created a Mac project on github that should just work (both building and debugging):

vscode-mac-c-example

Note that it requires XCode and the VSCode Microsoft cpptools extension.

I plan to do the same for Windows and linux (unless Microsoft write decent documentation first...).

泪冰清 2025-02-14 14:30:58

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

  1. 代码Runner
  2. C/C ++

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

First of all, goto extensions (Ctrl + Shift + X) and install 2 extensions:

  1. Code Runner
  2. C/C++

Then, then reload the VS Code and select a play button on the top of the right corner your program runs in the output terminal. You can see output by Ctrl + Alt + N.
To change other features goto user setting.
enter image description here

月亮是我掰弯的 2025-02-14 14:30:58

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

  1. 一般C ++语言支持编辑器。这通常是使用MS-VSCODE.CPPTOOLS完成的,大多数人也希望它处理许多其他内容,例如构建支持。让我节省一些时间:没有。但是,无论如何您都可能想要它。

  2. 构建,清洁和重建任务。在这里,您选择的构建系统将成为一件大事。您会找到诸如CMAKE和AUTOCONF(上帝帮助您)之类的内容的插件,但是如果您使用Meson和Ninja之类的东西,则必须编写一些助手脚本,并配置一个自定义“ Tasks.json”文件处理这些。微软在最后几个版本上完全更改了有关该文件的所有内容,直到应该被称为它的内容,并且可以完全更改格式的位置(是的,是的位置)。更糟糕的是,他们有点向后兼容,以确保使用“版本”键指定所需的变体。请参阅此处的详细信息:

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

...但请注意与:

https://code.visualstudio.com/docs/docs/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
                }
            }
        }
    ]
}

请注意,从理论上讲,如果您将其放在工作空间root中,则该文件应该可以工作,以便您'' t将隐藏目录中的文件(.vscode)中的文件纳入您的修订控制系统。我还没有看到这实际上有效。测试它,但是如果失败,请将其放入.vscode中。无论哪种方式,如果不存在IDE,IDE都会bit子。 (是的,目前,这意味着我被迫检查.vscode to Subversion,我不满意。)请注意,我的构建脚本(未显示)只需创建(或重新创建)使用调试目录,我的情况,介子并在其中建造(在我的情况下,使用忍者)。

  1. 运行,调试,附件,停止。这些是“启动”中定义的另一组任务。或至少它们曾经是。微软制作了这样的文档,我什至不确定了。

The basic problem here is that building and linking a C++ program depends heavily on the build system in use. You will need to support the following distinct tasks, using some combination of plugins and custom code:

  1. 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.

  2. 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

...but note conflicts with:

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

WARNING: IN ALL OF THE ANSWERS BELOW, ANYTHING THAT BEGINS WITH A "VERSION" TAG BELOW 2.0.0 IS OBSOLETE.

Here's the closest thing I've got at the moment. Note that I kick most of the heavy lifting off to scripts, this doesn't really give me any menu entries I can live with, and there isn't any good way to select between debug and release without just making another three explicit entries in here. With all that said, here is what I can tolerate as my .vscode/tasks.json file at the moment:

{
    // 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+(.*)
quot;,
                    "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+(.*)
quot;,
                    "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+(.*)
quot;,
                    "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).

  1. Run, debug, attach, halt. These are another set of tasks, defined in "launch.json". Or at least they used to be. Microsoft has made such a hash of the documentation, I'm not even sure anymore.
迷雾森÷林ヴ 2025-02-14 14:30:58

这是我使用G ++编译器为C ++配置VS的方式,它的运作效果很好,包括调试选项:

tasks.json File.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"
}

File.json File.json File.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"
        }
    ]
}

Visual Studio Code of Visual Studio Code'安装在VS代码中

Here is how I configured my VS for C++ using g++ compiler and it works great including debugging options:

tasks.json file

{
    "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 file

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

I also have 'C/C++ for Visual Studio Code' extension installed in VS Code

别理我 2025-02-14 14:30:58

如果您的项目具有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> build> build 具有CMAKE配置的工作区。

还有一个 cmake Integration' cmake build“命令到vscode。

PS! QUASICEMATCHER 是为 clang -builds设置的。要使用GCC,我相信您需要将 fileLocation 更改为相对,但是我尚未对此进行测试。

If your project has a CMake configuration it's pretty straight forward to setup VSCode, e.g. setup tasks.json like below:

{
    "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+(.*)
quot;,
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        }
    ]
}

This assumes that there is a folder build in the root of the workspace with a CMake configuration.

There's also a CMake integration extension that adds a "CMake build" command to VScode.

PS! The problemMatcher is setup for clang-builds. To use GCC I believe you need to change fileLocation to relative, but I haven't tested this.

£烟消云散 2025-02-14 14:30:58

有了更新的VS代码,您可以按以下方式进行操作:

  1. hit( ctrl + p )和type:
ext install cpptools
  1. 打开一个文件夹( ctrl + k &amp; ctrl + o ),并使用扩展名 .cpp (例如: Hello.cpp ):


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

  3. hit( ctrl + shift + p 和type and type,配置任务跑步者,然后选择>列表底部的其他

  4. 代码
@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.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. hit( ctrl + shift + b b 以运行构建任务。这将创建<< strong> .obj 和 .exe 项目的文件。

  2. .exe 用于调试项目
  3. in 启动文件,编辑以下行,保存文件:

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

With an updated VS Code you can do it in the following manner:

  1. Hit (Ctrl+P) and type:
ext install cpptools
  1. Open a folder (Ctrl+K & Ctrl+O) and create a new file inside the folder with the extension .cpp (ex: hello.cpp):

  2. Type in your code and hit save.

  3. Hit (Ctrl+Shift+P and type, Configure task runner and then select other at the bottom of the list.

  4. Create a batch file in the same folder with the name build.bat and include the following code to the body of the file:

@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. Edit the task.json file as follows and save it:
{
    // 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. Hit (Ctrl+Shift+B to run Build task. This will create the .obj and .exe files for the project.

  2. For debugging the project, Hit F5 and select C++(Windows).

  3. In launch.json file, edit the following line and save the file:

"program": "${workspaceRoot}/hello.exe",
  1. Hit F5.
掩耳倾听 2025-02-14 14:30:58

可以使用Extension 代码跑步者通过快捷键在右上角的play图标运行代码: ctrl ++ alt ++ n 并流产 ctrl + alt + m 。但是默认情况下,它仅显示程序的输出,但要接收输入,您需要遵循一些步骤:

ctrl + ,然后打开设置菜单,扩展名&gt; run代码配置滚动向下滚动其属性和属性和在设置中查找编辑单击它,然后添加以下代码INSITE:

{
 "code-runner.runInTerminal": true
}

Can use Extension Code Runner to run code with play icon on top Right ans by shortcut key :Ctrl+Alt+N and to abort Ctrl+Alt+M. But by default it only shows output of program but for receiving input you need to follow some steps:

Ctrl+, and then settings menu opens and Extensions>Run Code Configuration scroll down its attributes and find Edit in settings.json click on it and add following code insite it :

{
 "code-runner.runInTerminal": true
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文