在Linux环境下调试C++程序有多种工具和方法,以下是主要的调试技术和工具:
GDB是最常用的Linux下C++调试工具。
# 编译时加入调试信息
g++ -g your_program.cpp -o your_program
# 启动GDB
gdb ./your_program
命令 | 功能 |
---|---|
break [file:]line/func |
设置断点 |
run [args] |
运行程序 |
next (n) |
单步执行(不进入函数) |
step (s) |
单步执行(进入函数) |
continue (c) |
继续执行到下一个断点 |
print var (p) |
打印变量值 |
backtrace (bt) |
查看调用栈 |
info locals |
显示当前局部变量 |
watch var |
设置观察点 |
quit (q) |
退出GDB |
LLDB是LLVM项目的一部分,功能与GDB类似但有一些现代特性。
# 安装LLDB
sudo apt-get install lldb # Ubuntu/Debian
# 使用
lldb ./your_program
Eclipse提供了集成的C/C++开发环境,包含图形化调试界面。
即使不是Qt项目,Qt Creator也提供了优秀的C++调试功能。
配置VS Code的C++插件后,可以设置断点和可视化调试。
检测内存泄漏和内存错误:
valgrind --leak-check=full ./your_program
GCC/Clang内置的内存错误检测工具:
g++ -fsanitize=address -g your_program.cpp -o your_program
g++ -pg your_program.cpp -o your_program
./your_program
gprof ./your_program gmon.out > analysis.txt
Linux内核提供的性能分析工具:
perf record ./your_program
perf report
当程序崩溃时,可以分析核心转储文件:
# 启用核心转储
ulimit -c unlimited
# 程序崩溃后
gdb ./your_program core
break if condition
tbreak
info threads
, thread n
disassemble
set var = value
对于复杂问题,结合日志输出和调试器:
#include <iostream>
#define DEBUG_LOG(x) std::cerr << #x << " = " << (x) << std::endl
掌握这些工具和技术可以大大提高在Linux下调试C++程序的效率。