如何使用VSCode + cppdbg调试Rust集成测试
在VSCode中用GDB调试Rust集成测试的配置方案
问题背景
之前我用CodeLLDB插件配合LLDB调试Rust集成测试,配置如下:
{ "version": "0.2.0", "configurations": [ { "type": "lldb", "request": "launch", "name": "run integration test", "sourceLanguages": ["rust"], "cargo": { "args": [ "test", "--package=name_of_my_package", "--no-run", "--tests", ], "filter": { "kind": "test" } }, "args": [ "--exact", "--nocapture", "name_of_my_test", ], "cwd": "${workspaceFolder}", }, ], }
现在想改用GDB(它的枚举支持远优于LLDB),但cpptools扩展(调试类型为cppdbg)不支持cargo指令,核心问题是没法直接获取带非确定性哈希的测试二进制文件路径,需要等效配置或替代方案。
解决方案
方案1:Tasks+Launch联动(稳定可靠,适配cpptools)
先创建.vscode/tasks.json,负责编译测试并把二进制复制到固定路径:
{ "version": "2.0.0", "tasks": [ { "label": "build test for gdb", "type": "shell", "command": "cargo test --package=name_of_my_package --no-run --tests && cp $(find ./target/debug/deps -name '*name_of_my_test-*' -type f) ./target/debug/my_test_fixed", "problemMatcher": ["$rustc"], "group": "build" } ] }
这条命令先编译测试(--no-run避免自动执行),再通过find定位到带测试名的二进制文件,复制到./target/debug/my_test_fixed这个固定路径。
再创建.vscode/launch.json配置cpptools:
{ "version": "0.2.0", "configurations": [ { "name": "Debug Integration Test (GDB)", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/target/debug/my_test_fixed", "args": ["--exact", "--nocapture", "name_of_my_test"], "cwd": "${workspaceFolder}", "MIMode": "gdb", "setupCommands": [ { "text": "-enable-pretty-printing", "ignoreFailures": true } ], "preLaunchTask": "build test for gdb" } ] }
preLaunchTask会在调试前自动执行编译复制任务,确保固定路径的二进制是最新的,之后GDB就能直接启动它。
方案2:用支持Cargo的GDB扩展(更省心)
如果不想手动处理路径,可以用Rust Debugger (GDB)扩展,它直接支持cargo指令,配置和CodeLLDB几乎一致:
{ "version": "0.2.0", "configurations": [ { "type": "gdb", "request": "launch", "name": "Debug Integration Test (GDB)", "cargo": { "args": [ "test", "--package=name_of_my_package", "--no-run", "--tests" ], "filter": { "kind": "test", "name": "name_of_my_test" } }, "args": ["--exact", "--nocapture"], "cwd": "${workspaceFolder}", "gdbpath": "gdb" } ] }
这个扩展会自动解析Cargo生成的测试二进制路径,不用管哈希问题。
方案3:软链接替代复制(可选)
如果不想复制文件,也可以把tasks.json里的cp换成软链接命令(Linux/macOS用ln -sf,Windows用mklink),比如:
# Linux/macOS cargo test --package=name_of_my_package --no-run --tests && ln -sf $(find ./target/debug/deps -name '*name_of_my_test-*' -type f) ./target/debug/my_test_fixed
内容的提问来源于stack exchange,提问作者ChrisB
相关产品推荐
相关产品推荐

