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


本篇博客以一個簡單的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": [    //編譯參數列表
                "-g", // 加上-g可以斷點調試
                "main.cpp",
                "-o",
                "main.out"
            ]
        }
    ]
}

上面的command是我們的編譯命令,args是編譯參數列表,合在一起,其實就是我們手動編譯時的命令。

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字符串。在程序中添加斷點,調試時也會在斷點處中斷。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM