一、前提须知
必须确保你的cmake文件能够编译通过,并可以通过make生成可执行文件
二、具体步骤
1.设置CMakeLists.txt
set(CMAKE_BUILD_TYPE DEBUG)
2.VScode调试
VScode调试底层是调用gdb,因此需要修改配置launch.json文件为:
{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/MROR_exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
program为你make生成可执行文件的路径配置, MROR_exe为add_executable生成的可执行文件名称。
三、编译并调试
cmake ..
make
一定要提前确保你的程序能够编译并且运行,否则不能调试!
给你的程序打上断点,然后按F5,进入调试
四、正常来说上述已经可以进行调试了,但是需要手动cmake,比较麻烦,下面介绍一种直接自动编译调试的方法
1.在vscode配置task.json为:
{
"version": "2.0.0",
"options": {
"cwd": "${workspaceFolder}/build"
},
"tasks": [
{
"type": "shell",
"label": "cmake_label",
"command": "cmake",
"args": [
"-DCMAKE_BUILD_TYPE=Debug",
".."
]
},
{
"label": "make_label",
"group": {
"kind":"build",
"isDefault": true
},
"command": "make"
},
{
"label": "Build_label",
"dependsOrder": "sequence",
"dependsOn": [
"cmake_label",
"make_label"
]
}
]
}
2.并且在上述的launch.json加入一行"preLaunchTask": "Build_label"
即:
{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/MROR_exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "Build_label",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
配置完成之后,直接按F5,相当于执行了一个prelaunchtask的任务,自动cmake ..&& make