码迷,mamicode.com
首页 > 编程语言 > 详细

linux系统下如何在vscode中调试C++代码

时间:2018-11-04 00:24:37      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:ons   extern   一个   microsoft   image   get   label   正方形   编译参数   

本篇博客以一个简单的hello world程序,介绍在vscode中调试C++代码的配置过程。

1. 安装编译器

vscode是一个轻量的代码编辑器,并不具备代码编译功能,代码编译需要交给编译器完成。linux下最常用的编译器是gcc,通过如下命令安装:

sudo apt-get install build-essential

安装成功之后,在终端中执行gcc --version或者g++ --version,可以看到编译器的版本信息,说明安装成功。

2. 安装必要的插件

在vscode中编写C++代码,C/C++插件是必不可少的。打开vscode,点击左边侧边栏最下面的正方形图标,在搜索框里输入c++,安装插件。
技术分享图片

3. 编写代码

hello world程序,略。

4. 配置task

在task里添加编译命令,从而执行编译操作。步骤如下:

  • 按住ctrl+shift+P,打开命令面板;
  • 选择Configure Tasks...,选择Create tasks.json file from templates,之后会看到一系列task模板;
  • 选择others,创建一个task,下面是一个task的示例:
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build hello world",     // task的名字
            "type": "shell",   
            "command": "g++",    //编译命令
            "args": [    //编译参数列表
                "main.cpp",
                "-o",
                "main.out"
            ]
        }
    ]
}

上面的command是我们的编译命令,args是编译参数列表,合在一起,其实就是我们手动编译时的命令。

g++ main.cpp -0 main.out

5. 配置launch.json

把debug的内容配置在launch.json,这样我们就可以使用断点调试了。

  • 点击侧边栏的debug按钮,就是那只虫子图标;
  • 在上面的debug栏目里,点击齿轮图标;
  • 在下拉菜单中选择 C++ (GDB/LLDB),这时会在.vscode文件夹下创建一个lauch.json文件,用来配置debug;下面是launch.json文件的一个示例:
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "debug hello world",    //名称
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/main.out",    //当前目录下编译后的可执行文件
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",    //表示当前目录
            "environment": [],
            "externalConsole": false, // 在vscode自带的终端中运行,不打开外部终端
            "MIMode": "gdb",    //用gdb来debug
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "build hello world"    //在执行debug hello world前,先执行build hello world这个task,看第4节
        }
    ]
}

6. 结束

至此,配置完成,按F5可以编译和调试代码,vscode自带终端中会打印hello world字符串。在程序中添加断点,调试时也会在断点处中断。

linux系统下如何在vscode中调试C++代码

标签:ons   extern   一个   microsoft   image   get   label   正方形   编译参数   

原文地址:https://www.cnblogs.com/jiaxblog/p/9902535.html

(0)
(1)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!