在 Debian 上调试 Rust 程序
一 环境准备
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shsource $HOME/.cargo/envsudo apt update && sudo apt install gdb lldbrustup component add rust-src llvm-tools-previewrust-gdb/rust-lldb 为增强封装,提供更友好的 Rust 语法支持。二 构建与符号
cargo build(生成于 target/debug/)Cargo.toml 的 [profile.release] 中设置:debug = truecargo build --releasecargo install 默认以 release 构建;如需调试版,使用:cargo install --debug <crate>。三 使用 GDB 调试
rust-gdb target/debug/your_binarybreak main 或 break your_crate::your_functionrun(可带参数:run arg1 arg2)step(进入函数)/ next(不进入)continueprint variable 或 print expressionbacktrace(简写 bt)break your_function if variable == 42-enable-pretty-printing)。四 使用 LLDB 调试
rust-lldb target/debug/your_binaryb binary_search 或 breakpoint set -f main.rs -l 42r(可预设参数:settings set target.run-args "arg1 arg2")thread step-in(step)/ thread step-over(next)continueframe variableexpr size == 24watch set var basebreakpoint set -c "half == 3" -f main.rs -l 13 -C btrust-lldb 提供对 Rust 类型与名称更友好的展示。五 进阶与 IDE 集成
strace -p <PID> 或 strace -e trace=open,read,write -p <PID>ltrace -p <PID>Vec/String 等容器有良好支持):
sudo apt install valgrindvalgrind --tool=memcheck target/debug/your_binaryprintln! 与 dbg! 快速打印调试信息;dbg!(x) 会输出文件名、行号与值。log + env_logger,运行时设置 RUST_LOG=info cargo runcargo install cargo-watch 后执行 cargo watch -x run.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 }cargo deb 时默认会剥离调试符号;可通过 cargo deb --separate-debug-symbols 将符号分离打包,便于后续 gdb/lldb 加载调试。