https://www.cnblogs.com/lonelycatcher/archive/2011/10/09/2204865.html
例子:
[root@localhost ~/test/test_2]
# cat -n test.c
1 #include <stdio.h>
2
3 int
4 main(int argc, char *const argv[])
5 {
6 int i = 0;
7 int a = 0;
8
9 for (i = 0; i < 10; i++) {
10 a += i;
11 }
12 return 0;
13 }
编译:
[root@localhost ~/test/test_2]
# gcc -g test.c -o test
[root@localhost ~/test/test_2]
# ls
test test.c
运行gdb并使用watch
[root@localhost ~/test/test_2]
# gdb ./test
GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-114.el7
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /root/test/test_2/test...done.
(gdb) list
1 #include <stdio.h>
2
3 int
4 main(int argc, char *const argv[])
5 {
6 int i = 0;
7 int a = 0;
8
9 for (i = 0; i < 10; i++) {
10 a += i;
(gdb) break 7
Breakpoint 1 at 0x400502: file test.c, line 7.
(gdb) r
Starting program: /root/test/test_2/./test
Breakpoint 1, main (argc=1, argv=0x7fffffffe5a8) at test.c:7
7 int a = 0;
Missing separate debuginfos, use: debuginfo-install glibc-2.17-260.el7.x86_64
(gdb) watch a
Hardware watchpoint 2: a
(gdb) c
Continuing.
Hardware watchpoint 2: a
Old value = 0
New value = 1
main (argc=1, argv=0x7fffffffe5a8) at test.c:9
9 for (i = 0; i < 10; i++) {
(gdb) c
Continuing.
Hardware watchpoint 2: a
Old value = 1
New value = 3
main (argc=1, argv=0x7fffffffe5a8) at test.c:9
9 for (i = 0; i < 10; i++) {
(gdb) c
Continuing.
Hardware watchpoint 2: a
Old value = 3
New value = 6
main (argc=1, argv=0x7fffffffe5a8) at test.c:9
9 for (i = 0; i < 10; i++) {
(gdb) c
Continuing.
Hardware watchpoint 2: a
Old value = 6
New value = 10
main (argc=1, argv=0x7fffffffe5a8) at test.c:9
9 for (i = 0; i < 10; i++) {
(gdb) quit
A debugging session is active.
Inferior 1 [process 7014] will be killed.
Quit anyway? (y or n) y
[root@localhost ~/test/test_2]
总结:
使用gdb的watch功能,需要break、run、watch和continue结合起来使用。
1、先使用break把断点设置到变量定义处;
2、运行run命令,使程序执行到断点处;
3、使用watch命令来观察变量,变量一旦发生变化就显示出来;
4、使用continue继续运行,并观察watch显示的信息。