我试图通过命令“watch a”来观察“int a”的变化。但是,程序不会停止,当它变为12.为什么?
/* FILE: test.c */
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv){
printf("Hello world\n");
int a = 12;
a = 10;
return 0;
}
答案 0 :(得分:11)
指定您的平台,GDB版本以及您使用的GDB命令的确切顺序可能会有所帮助。
这是我看到的(GDB似乎工作正常):
$ gcc -g test.c
$ gdb a.out
GNU gdb (GDB) 6.8.50.20090430-cvs
Copyright (C) 2009 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-unknown-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
(gdb) list
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main(int argc, char** argv){
5 printf("Hello world\n");
6
7 int a = 12;
8 a = 10;
9 return 0;
10 }
11
(gdb) b 5
Breakpoint 1 at 0x4004a7: file test.c, line 5.
(gdb) r
Breakpoint 1, main (argc=1, argv=0x7fffffffdb28) at test.c:5
5 printf("Hello world\n");
(gdb) watch a
Hardware watchpoint 2: a
(gdb) c
Hello world
Hardware watchpoint 2: a
Old value = 0
New value = 12
main (argc=1, argv=0x7fffffffdb28) at test.c:8
8 a = 10;
(gdb) c
Hardware watchpoint 2: a
Old value = 12
New value = 10
main (argc=1, argv=0x7fffffffdb28) at test.c:9
9 return 0;
(gdb) c
Watchpoint 2 deleted because the program has left the block in
which its expression is valid.
0x00007ffff7ab3033 in exit () from /lib/libc.so.6
(gdb) c
Program exited normally.
(gdb) q
答案 1 :(得分:3)
当您想要调试程序时,您应该始终使用-O0 -g3构建(我认为您使用的是gcc,如果您不是您的编译器,可能会支持其他标志来关闭优化并启用调试信息)。 / p>
在我的系统上(运行Gentoo GNU / Linux的x86_64)当我使用大于或等于-O的任何优化时,我无法进入'int a = 12'行,因为编译器将应用dead code elimination 。 (取自here,它是-O部分中的-fdce标志)
调试时始终牢记这一点!通过使用objdump -D反汇编代码来验证您的代码,或者告诉编译器向您展示生成的程序集(在带有-S标志的gcc上)
答案 2 :(得分:1)
编译器甚至可能无法生成将12分配给“a”的代码,因此最好反汇编生成的代码以进行确认。你可能需要一个稍微复杂的测试来试试这个。