gdb 编译代码与调试分离
Remote GDB Debugging with C++ — Source Code Strategies
When C++ code is compiled on a dev machine (A) and debugged on a target machine (B), GDB needs to find matching source files. Here are the options, from best to worst.
1. Best: Use gdbserver (no source copy to target)
Run a thin gdbserver on the target; connect full GDB from the dev machine where sources live.
|
|
Build requirement: the binary on both sides must match exactly (same build artifact).
2. Good: Compile with path remapping, then copy sources anywhere
At compile time on machine A, remap the absolute source paths in the DWARF debug info:
|
|
Then on the target machine B, copy sources to the remapped path:
|
|
GDB on machine B finds them automatically because DWARF now contains /opt/src/project/...
instead of /home/user/project/....
3. Flexible: Use set substitute-path in GDB
If you already built without -fdebug-prefix-map, redirect at debug time:
|
|
Add this to ~/.gdbinit on the target to make it permanent.
4. Quick: Use the directory command
Point GDB to the copied source tree:
|
|
This adds /tmp/src to the source search path. Simpler than substitute-path but only works
if the relative directory structure under the DWARF path matches.
5. Last resort: Copy sources to the exact same absolute path
|
|
Fragile — only works when usernames and paths are identical across machines.
Summary
| Method | Copy sources to target? | Effort |
|---|---|---|
gdbserver |
No | Low (best) |
-fdebug-prefix-map at build |
Yes (to a fixed path) | Medium |
set substitute-path |
Yes (any path) | Low |
directory |
Yes (any path) | Low |
| Same absolute path | Yes (exact path) | Low (fragile) |
Recommendation: If you control the build, add -fdebug-prefix-map to your CMake/Makefile.
If you don’t, use gdbserver — it’s the cleanest workflow and avoids source-sync problems entirely.
相关内容
支付宝
微信

william