Debian上如何调试Rust程序
导读:在 Debian 上调试 Rust 程序 一 环境准备 安装 Rust 工具链(若尚未安装): 执行:curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh 加载环境...
在 Debian 上调试 Rust 程序
一 环境准备
- 安装 Rust 工具链(若尚未安装):
- 执行:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh - 加载环境:
source $HOME/.cargo/env
- 执行:
- 安装调试器与 Rust 增强脚本:
sudo apt update & & sudo apt install gdb lldbrustup component add rust-src llvm-tools-preview
- 说明:Rust 使用 DWARF 调试信息,可直接配合 GDB/LLDB;
rust-gdb/rust-lldb为增强封装,提供更友好的 Rust 语法支持。
二 构建与符号
- 调试构建:使用 debug 模式(默认),保留调试符号与更友好的堆栈信息。
cargo build(生成于 target/debug/)
- 若需在 release 模式下保留调试信息(便于定位优化后的崩溃):
- 在
Cargo.toml的[profile.release]中设置:debug = true - 构建:
cargo build --release
- 在
- 注意:
cargo install默认以 release 构建;如需调试版,使用:cargo install --debug < crate>。
三 使用 GDB 调试
- 启动调试会话:
rust-gdb target/debug/your_binary
- 常用命令:
- 断点:
break main或break your_crate::your_function - 运行:
run(可带参数:run arg1 arg2) - 单步:
step(进入函数)/next(不进入) - 继续:
continue - 打印:
print variable或print expression - 调用栈:
backtrace(简写bt) - 条件断点:
break your_function if variable == 42
- 断点:
- 提示:启用 GDB 的 Rust 美化打印可提升可读性(见 VS Code 配置示例中的
-enable-pretty-printing)。
四 使用 LLDB 调试
- 启动调试会话:
rust-lldb target/debug/your_binary
- 常用命令(LLDB 命令族风格):
- 断点:
b binary_search或breakpoint set -f main.rs -l 42 - 运行:
r(可预设参数:settings set target.run-args "arg1 arg2") - 单步:
thread step-in(step)/thread step-over(next) - 继续:
continue - 变量:
frame variable - 表达式求值:
expr size == 24 - 监视点:
watch set var base - 条件断点并自动打印堆栈:
breakpoint set -c "half == 3" -f main.rs -l 13 -C bt
- 断点:
- 说明:
rust-lldb提供对 Rust 类型与名称更友好的展示。
五 进阶与 IDE 集成
- 系统调用与库调用跟踪(定位 I/O、系统调用、库函数问题):
- 跟踪系统调用:
strace -p < PID>或strace -e trace=open,read,write -p < PID> - 跟踪库函数:
ltrace -p < PID>
- 跟踪系统调用:
- 内存错误与泄漏检测(对 Rust 的
Vec/String等容器有良好支持):sudo apt install valgrindvalgrind --tool=memcheck target/debug/your_binary
- 日志与快速迭代:
- 使用
println!与dbg!快速打印调试信息;dbg!(x)会输出文件名、行号与值。 - 结构化日志:
log+env_logger,运行时设置RUST_LOG=info cargo run - 文件变更自动构建运行:
cargo install cargo-watch后执行cargo watch -x run
- 使用
- VS Code 调试配置示例(使用 GDB):
- 安装扩展:rust-analyzer
.vscode/launch.json:- 配置要点:
type: cppdbg、request: launch、program: "${ workspaceFolder} /target/debug/your_binary"、MIMode: gdb、miDebuggerPath: "/usr/bin/gdb",并在setupCommands中加入-enable-pretty-printing
- 配置要点:
.vscode/tasks.json(构建任务):label: "cargo build",command: "cargo build",group: { kind: "build", isDefault: true }
- 打包与调试符号(Debian 包场景):
- 使用
cargo deb时默认会剥离调试符号;可通过cargo deb --separate-debug-symbols将符号分离打包,便于后续gdb/lldb加载调试。
- 使用
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Debian上如何调试Rust程序
本文地址: https://pptw.com/jishu/753707.html
