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

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

我寫了一個實例程序(不重要)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,這是一個啓動文件,咱們來配置它。shell

{
    // 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這個名字。json

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

這裏,它還須要一個task.json文件,配置以下,spa

{
    // 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便可開始調試代碼。debug

 

關於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文件中。code

我的感受多是項目比較簡單因此看不來它的好處。

相關文章
相關標籤/搜索