温馨提示×

Rust在Debian上的调试配置怎么做

小樊
37
2025-12-11 02:25:10
栏目: 编程语言

在 Debian 上配置 Rust 调试环境的完整步骤

一 安装工具链与调试器

  • 安装 Rust 工具链(rustup),便于管理版本与组件:
    • 执行:curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
    • 完成后执行:source $HOME/.cargo/env,将 ~/.cargo/bin 加入 PATH
  • 安装系统调试器与 Rust 增强调试组件:
    • 安装 gdblldbsudo apt update && sudo apt install gdb(或 sudo apt install lldb
    • 安装 Rust 调试脚本与源码组件:rustup component add rust-src llvm-tools-preview
    • 说明:安装后可使用 rust-gdb / rust-lldb 获得更好的 Rust 语法与类型支持

二 构建与符号配置

  • 调试构建:使用 cargo build(默认即调试配置,包含调试信息),生成的二进制位于 target/debug/;发布构建使用 cargo build --release,位于 target/release/
  • 在发布构建中保留调试信息(便于线上问题定位):
    • Cargo.toml[profile.release] 中设置:debug = true
    • 说明:开启后可在 release 二进制中保留调试符号,不影响优化级别

三 命令行调试流程

  • 使用 rust-gdb 调试调试构建:
    • 启动:rust-gdb target/debug/your_program
    • 常用命令:break mainrunnextstepprint xbacktrace
  • 使用 rust-lldb 调试调试构建:
    • 启动:rust-lldb target/debug/your_program
    • 常用命令:b mainrunnsframe variablebt
  • 崩溃时获取回溯:
    • 运行:RUST_BACKTRACE=1 cargo run(或 RUST_BACKTRACE=1 target/debug/your_program
    • 建议始终开启回溯,便于定位 panic 与异常

四 VS Code 调试配置

  • 安装扩展:
    • rust-analyzer(语言支持)
    • 调试器扩展:CodeLLDB(用于 LLDB)或 C/C++(内置 cppdbg,用于 GDB)
  • 配置 .vscode/launch.json(以 GDB 为例,调试构建):
    • 示例:
      {
        "version": "0.2.0",
        "configurations": [
          {
            "type": "cppdbg",
            "request": "launch",
            "name": "Debug",
            "program": "${workspaceFolder}/target/debug/${workspaceFolderBasename}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "/usr/bin/gdb",
            "setupCommands": [
              {
                "description": "Enable pretty-printing for gdb",
                "text": "-enable-pretty-printing",
                "ignoreFailures": true
              }
            ],
            "preLaunchTask": "cargo build"
          }
        ]
      }
      
    • 如需调试发布构建,将 program 改为 target/release/${workspaceFolderBasename},并将 preLaunchTask 改为 cargo build --release
  • 配置 .vscode/tasks.json(构建任务):
    {
      "version": "2.0.0",
      "tasks": [
        {
          "label": "cargo build",
          "type": "shell",
          "command": "cargo build",
          "group": { "kind": "build", "isDefault": true },
          "problemMatcher": ["$rustc"]
        }
      ]
    }
    
  • 使用 CodeLLDB 时:将 type 改为 lldb,并相应调整调试器路径与参数

五 内存与性能辅助工具

  • Valgrind(检测内存错误与泄漏,建议对调试构建使用):
    • 安装:sudo apt install valgrind
    • 运行:valgrind --tool=memcheck target/debug/your_program
  • gdb 的 pretty-printing:在 rust-gdb 中启用后,Rust 标准库类型(如 VecStringHashMap)能以更友好的方式显示,提升可读性

0