先来看一段代码:
这段代码的输出结果是:
-84
4294967264
xiaoqiang@dev:~/cpp$ g++ -g c212.cc -o temp xiaoqiang@dev:~/cpp$ ls c143.cc c144.cc c212.cc temp可以看到多出一个temp文件
xiaoqiang@dev:~/cpp$ gdb temp GNU gdb (Ubuntu/Linaro 7.4-2012.04-0ubuntu2.1) 7.4-2012.04 Copyright (C) 2012 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-linux-gnu". For bug reporting instructions, please see: <http://bugs.launchpad.net/gdb-linaro/>... Reading symbols from /home/xiaoqiang/cpp/temp...done. (gdb) list 1 #include <iostream> 2进入到gdb调试模式我们来看个究竟(gdb) b 6 Breakpoint 1 at 0x4007ea: file c212.cc, line 6.
3 int main(){4 unsigned u = 10;5 int i = -42;6 std::cout << i + i << std::endl;7 std::cout << u + i << std::endl;8 return 0;9 }(gdb)
(gdb) b 6 Breakpoint 1 at 0x4007ea: file c212.cc, line 6.开始运行,就会发现程序停在了第6行
(gdb) r Starting program: /home/xiaoqiang/cpp/temp warning: no loadable sections found in added symbol-file system-supplied DSO at 0x7ffff7ffa000 Breakpoint 1, main () at c212.cc:6 6 std::cout << i + i << std::endl; (gdb)我们来看看i的二进制值是多少
xiaoqiang@dev:~/cpp$ gdb temp GNU gdb (Ubuntu/Linaro 7.4-2012.04-0ubuntu2.1) 7.4-2012.04 Copyright (C) 2012 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-linux-gnu". For bug reporting instructions, please see: <http://bugs.launchpad.net/gdb-linaro/>... Reading symbols from /home/xiaoqiang/cpp/temp...done. (gdb) list 1 #include <iostream> 2 3 int main(){ 4 unsigned u1 = 42, u2 = 10; 5 std::cout << u1 - u2 << std::endl; 6 std::cout << u2 - u1 << std::endl; 7 return 0; 8 } (gdb)看一下u1和u2的二进制表示
Breakpoint 1, main () at c213.cc:5 5 std::cout << u1 - u2 << std::endl; (gdb) next 32 6 std::cout << u2 - u1 << std::endl; (gdb) next 4294967264 7 return 0; (gdb) print /t u2 $2 = 1010 (gdb) print /t u1 $3 = 101010 (gdb)差值为11111111 111111111 11111111 11100000