在Ubuntu上调试C++代码可以通过多种工具和步骤来实现,以下是一些便捷的方法:
.vscode
文件夹。.vscode
文件夹中创建tasks.json
和launch.json
文件。tasks.json用于配置编译任务:
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "g++",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
launch.json用于配置调试任务:
{
"version": "0.2.0",
"configurations": [
{
"name": "g++",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"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",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
F5
键或点击工具栏上的绿色调试箭头图标启动调试会话。sudo apt update
sudo apt install gdb
-g
标志以包含调试信息:g++ -g -o my_program my_program.cpp
gdb my_program
break main
run
next
:单步跳过函数调用step
:单步进入函数continue
:继续执行程序直到遇到下一个断点print variable_name
:打印变量的值backtrace
:显示当前调用堆栈Valgrind是一套Linux下的仿真调试工具集合,特别擅长检测内存泄漏问题:
sudo apt install valgrind
valgrind --leak-check=yes ./my_program
lxrunoffline
工具简化WSL2的使用。通过上述方法,你可以在Ubuntu上便捷地调试C++代码,选择适合你工作流程的工具和步骤,可以大大提高调试效率和代码质量。