1. 程式人生 > >ubuntu下VS code如何調試C++代碼

ubuntu下VS code如何調試C++代碼

works ngs 比較 tps 總結 locate sof chapter 官方

最近開始使用Vs codel,真的方便,可以和git結合。下面總結一下如何調試程序,

我寫了一個實例程序(不重要)

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main(void)
{
    fstream iofile("test.txt");
    vector<string> strs(20);
    int i=0;
    
if(!iofile){ cerr<<"open file failed"<<endl; }else{ while(iofile>>strs[i++]); } for(int j=0;j<i-1;j++) { cout<<strs[j]<<endl; } // cout<<endl; cout<<"after sort"<<endl; cout<<*(strs.begin())<<endl; sort(strs.begin(),strs.begin()
+i-1); cout<<"i:"<<i<<" "<<strs[1]<<endl; for(int j=0;j<i;j++) { cout<<strs[j]<<" "; } cout<<endl; return 0; }

這個時候,我們按F5,發現不能運行,它提示需要一個Launch.json文件,OK,這是一個啟動文件,我們來配置它。

{
    // 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": "(gdb) Launch", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/build", "preLaunchTask": "build", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": true, "MIMode": "gdb", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true } ] } ] }

註意,這裏需要修改的部分主要是program那一行,僅需修改為自己編譯後產生的文件名,不如g++ -g 1.7.cpp -o build,所以這裏我就取了build這個名字。

還有,就是要添加preLaunchTask這一行,名字與下面的task要對應。

這裏,它還需要一個task.json文件,配置如下,

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "shell",
            "command": "g++",
            "args": [
                "-g",
                "${workspaceFolder}/chapter01/1.7.cpp",
                "-o",
                "build"
            ]
        }
    ]
}

大家可以看到,這裏只需要將label的值要與上面的preLaunchTask相對應,其他的就是命令行部分,完成這個文件後,我們ctrl+shift+b,這是會執行task。

之後,我們打開main文件,設置斷點,F5即可開始調試代碼。

關於Launch.json:

官方是這樣說的:However, for most debugging scenarios, creating a launch configuration file is beneficial because it allows you to configure and save debugging setup details. VS Code keeps debugging configuration information in a launch.json file located in a .vscode folder in your workspace (project root folder) or in your user settings or workspace settings.但是,對於大多數調試方案,創建啟動配置文件是有益的,因為它允許您配置和保存調試設置詳細信息。 VS Code將配置信息保存在位於工作區(項目根文件夾)的.vscode文件夾或用戶設置或工作區設置中的launch.json文件中。

個人感覺可能是項目比較簡單所以看不來它的好處。

ubuntu下VS code如何調試C++代碼