在Linux环境下使用C++进行编程时,调试程序是一个非常重要的环节。以下是一些常用的调试方法和工具:
GDB是Linux下最强大的调试器之一,可以用来调试C/C++程序。
gdb your_program
break main
run
step
next
print variable_name
continue
quit
gdb ./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项目的调试器,也可以用来调试C/C++程序。
lldb your_program
breakpoint set --name main
run
step
next
frame variable
continue
quit
lldb ./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是一个非常流行的代码编辑器,内置了对GDB和LLDB的支持。
.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 --leak-check=full ./your_program
valgrind --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)
通过这些工具和方法,你可以在Linux环境下高效地调试C++程序。