C++代码在Ubuntu上的调试方法
GDB是Ubuntu下最常用的命令行调试工具,适合习惯终端操作的用户。
sudo apt update && sudo apt install gdb安装。-g选项编译C++文件,例如g++ -g main.cpp -o my_program(-g会将源代码信息嵌入可执行文件,是GDB调试的必要条件)。gdb ./my_program,加载可执行文件。break <位置>:设置断点(如break main在main函数开头断点,break main.cpp:10在第10行断点);run(或r):启动程序,运行至断点处暂停;next(或n):单步执行,不进入函数内部;step(或s):单步执行,进入函数内部;print <变量名>(或p):打印变量当前值(如print count);backtrace(或bt):查看函数调用栈,定位错误发生的位置;continue(或c):继续执行程序,直到下一个断点或程序结束;quit:退出GDB。VS Code是轻量级编辑器,通过扩展支持C++调试,适合偏好图形界面的用户。
.vscode文件夹;tasks.json文件(用于定义编译任务),内容参考:{
"version": "0.2.0",
"configurations": [
{
"label": "g++ build active file",
"type": "shell",
"command": "g++",
"args": ["-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}"],
"group": {"kind": "build", "isDefault": true},
"problemMatcher": ["$gcc"]
}
]
}
launch.json文件(用于配置调试参数),内容参考:{
"version": "0.2.0",
"configurations": [
{
"name": "g++ build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [{"description": "Enable pretty-printing", "text": "-enable-pretty-printing", "ignoreFailures": true}],
"preLaunchTask": "g++ build active file"
}
]
}
F5键启动调试,程序会在断点处暂停,通过顶部调试工具栏进行单步执行、继续、查看变量等操作。valgrind --leak-check=full ./my_program,会输出内存错误详情(如未释放的内存块)。strace ./my_program,可查看程序执行过程中的所有系统调用。