发布于2026-07-13 阅读(0)
扫一扫,手机访问
在Linux环境下用C++写代码,调试这件事儿迟早要面对。不管你是刚入门还是写过几年,总会在某个深夜盯着段错误(Segmentation Fault)发呆——这时候,手头那几把调试利器就是你的救命稻草。下面把几个最常用的方法和工具梳理一下,希望能帮你少走弯路。

GDB是Linux下历史最久、功能最全的调试器,没有之一。很多老派的C++开发者基本天天跟它打交道。它的学习曲线稍微陡了一点,但一旦上手,你会觉得“没有GDB这代码我都没法写”。
gdb your_programbreak mainrunstep或next
print variable_namecontinuequitgdb ./my_program
(gdb) break main
Breakpoint 1 at 0x401136: file my_program.cpp, line 10.
(gdb) run
Starting program: /path/to/my_program
Breakpoint 1, main () at my_program.cpp:10
10 int x = 5;
(gdb) next
11 int y = x + 3;
(gdb) print x
$1 = 5
(gdb) continue
Continuing.
LLDB是LLVM项目里的调试器,近几年发展很快,尤其是在macOS上已经成为默认工具。但Linux下也能用,而且它的命令风格比GDB稍微现代一些。如果你习惯LLVM生态,LLDB是个很好的选择。
lldb your_programbreakpoint set --name mainrunstep或next
frame variablecontinuequitlldb ./my_program
(lldb) breakpoint set --name main
Breakpoint 1: where = my_program`main + 10 at my_program.cpp:10, address = 0x0000000100001136
(lldb) run
Process 12345 launched: '/path/to/my_program' (x86_64)
Process 12345 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
frame #0: 0x0000000100001136 my_program`main + 10
7 int x = 5;
8 int y = x + 3;
9 return 0;
-> 10 }
(lldb) frame variable
x = 5
y = 8
(lldb) continue
Process 12345 resuming
现在很多开发者更偏爱图形界面。VS Code配合C/C++扩展,可以无缝对接GDB或LLDB,调试体验跟IDE几乎一样。配置起来也不复杂,唯一需要你动手的就是写一份launch.json文件。
.vscode/launch.json文件,填入调试配置。launch.json{
"version": "0.2.0",
"configurations": [
{
"name": "Debug C++ Program",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/your_program",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "build"
}
]
}
调试段错误和逻辑错误是一回事,但内存泄漏、非法内存访问这种“慢性病”光靠断点是很难抓的。这时候就得请出Valgrind。它是个内存调试和分析工具,能帮你揪出那些程序跑完也看不出来的问题。说实话,很多线上崩溃的根因,都是靠Valgrind一层层扒出来的。
valgrind --leak-check=full ./your_programvalgrind --leak-check=full ./my_program
==12345== Memcheck, a memory error detector
==12345== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==12345== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==12345== Command: ./my_program
==12345==
==12345== HEAP SUMMARY:
==12345== in use at exit: 0 bytes
==12345== total heap usage: 1 allocs, 1 frees, 1,073,741,824 bytes allocated
==12345==
==12345== All heap blocks were freed -- no leaks are possible
==12345==
==12345== For lists of detected and suppressed errors, rerun with: -s
==12345== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
上面这四把刀——GDB、LLDB、VS Code + 扩展、Valgrind——基本涵盖了Linux下C++调试的绝大多数场景。平时自己写练习项目可以先用GDB练练手;团队协作或者需要快速定位问题时,VS Code的图形化调试显然更高效。至于Valgrind,建议养成编译完就跑一遍的习惯,很多隐形的坑能提前填上。调试这事没什么捷径,多上手、多踩坑,自然就熟练了。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8