1.建立工程文件,文件树如下
2.make.sh脚本文件如下
#! /bin/bash
cmake ..
make
重要 !!! !!! !!! !!! !!! 必须添加权限 sudo chmod +x make.sh
3.CMakelist文件如下
cmake_minimum_required(VERSION 3.16) # 版本要在3.16及以上
project(GDB)
set(CMAKE_CXX_STANDARD 14)
SET(CMAKE_BUILD_TYPE DEBUG) #调试模式这句话必不可少!
add_executable(HelloGDB main.cpp fun.h)
target_link_libraries(HelloGDB pthread) #多线程要链接库文件pthread
3.回到主函数界面,F5
自动生成了如下文件夹
4.新建launch.json文件,编辑launch.json文件,Add Configuration…
launch是编译运行选项,attach是附加进程调试功能
5.选择launch方式,编译运行方式
{
"configurations": [
{
"name": "Debug HelloVS",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/HelloGDB",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}/build",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
{
"description": "Set Disassembly Flavor to Intel",
"text": "-gdb-set disassembly-flavor intel",
"ignoreFailures": true
}
],
"preLaunchTask": "Build HelloVS",
"miDebuggerPath": "/usr/bin/gdb",
"sudo":true
}
]
}
"program": "${workspaceFolder}/build/HelloGDB" # 指定待调试的可执行文件的目录
6.编辑tasks.json文件
{
"tasks": [
{
"type": "cppbuild",
"label": "Build HelloVS",
"command": "./make.sh",
"args": [
],
"options": {
"cwd": "${workspaceFolder}/build"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
"label": "Build HelloVS" #这里的Build HelloVS与launch.json文件里的"preLaunchTask": "Build HelloVS" 名称必须一致,launch.json的预备工作就是执行Build HelloVS的工作,即编译工作
"cwd": "${workspaceFolder}/build" #指定make.sh文件的目录
"command": "./make.sh" #执行make.sh文件,必须得chmod +x make.sh
"args": [] #make的参数不需要指定,为空
7.回到主函数文件,F5执行两次
8.另一种方式 Attach,调试运行中的程序
launch文件如下:
{
"configurations": [
{
"name": "(gdb) Attach",
"type": "cppdbg",
"request": "attach",
"program": "${workspaceFolder}/build/HelloGDB",
"processId": "${command:pickProcess}",
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
{
"description": "Set Disassembly Flavor to Intel",
"text": "-gdb-set disassembly-flavor intel",
"ignoreFailures": true
}
]
},
{
"name": "Debug HelloVS",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/HelloGDB",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}/build",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
{
"description": "Set Disassembly Flavor to Intel",
"text": "-gdb-set disassembly-flavor intel",
"ignoreFailures": true
}
],
"preLaunchTask": "Build HelloVS",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
9.先运行程序
10.选择attach方式调试
F5执行,输入待调试函数名称即可