linux系統下如何在vscode中調試C++代碼

本篇博客以一個簡單的hello world程序,介紹在vscode中調試C++代碼的配置過程。linux

1. 安裝編譯器

vscode是一個輕量的代碼編輯器,並不具有代碼編譯功能,代碼編譯須要交給編譯器完成。linux下最經常使用的編譯器是gcc,經過以下命令安裝:c++

sudo apt-get install build-essential

安裝成功以後,在終端中執行gcc --version或者g++ --version,能夠看到編譯器的版本信息,說明安裝成功。shell

2. 安裝必要的插件

在vscode中編寫C++代碼,C/C++插件是必不可少的。打開vscode,點擊左邊側邊欄最下面的正方形圖標,在搜索框裏輸入c++,安裝插件。
json

3. 編寫代碼

hello world程序,略。編輯器

4. 配置task

在task裏添加編譯命令,從而執行編譯操做。步驟以下:ui

  • 按住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是編譯參數列表,合在一塊兒,其實就是咱們手動編譯時的命令。spa

g++ main.cpp -o main.out

5. 配置launch.json

把debug的內容配置在launch.json,這樣咱們就能夠使用斷點調試了。插件

  • 點擊側邊欄的debug按鈕,就是那隻蟲子圖標;
  • 在上面的debug欄目裏,點擊齒輪圖標;
  • 在下拉菜單中選擇 C++ (GDB/LLDB),這時會在.vscode文件夾下建立一個launch.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字符串。在程序中添加斷點,調試時也會在斷點處中斷。debug

相關文章
相關標籤/搜索