使用gdb调用printDebug方法

Use gdb to call a printDebug method

本文关键字:方法 printDebug 调用 gdb 使用      更新时间:2023-10-16

我有一个带有printDebug方法的类。它在代码中的任何地方都没有使用,但我想在使用gdb(使用调用)进行调试时使用它。这基本上是以一种格式良好的方式打印对象的内容,例如,我可能有一个集合的向量。g++选项是什么?我试过-O0,但不起作用。

我使用的解决方案是在构造函数中调用psuedo来调试print,并提供一个bool,指示您是真的想打印还是什么都不做。这很好,但必须有更好的方法。

如果我理解正确,O0不应该做任何优化,所以死代码不应该被删除,但也许我错了。

如果你有一个方法没有在代码中的任何地方使用gcc智能功能可以识别它,并在编译应用程序时忽略它。这就是为什么当您显示应用程序的符号(使用nm)时,该方法不会显示在结果上。

但是,如果要强制编译该方法,则需要在方法声明上指定_属性_used。例如:

  1 
  2 #include <iostream>
  3 #include <stdio.h>
  4 
  5 
  6 class aClass
  7 {
  8     public:
  9         void __attribute__ ((used)) publicPrint()
 10         {
 11             std::cout << "public method" << std::endl;
 12         }
 13 };
 14 
 15 
 16 int main()
 17 {
 18     aClass my_obj;
 19 
 20     getchar();
 21 }

出于测试目的,我使用-g:编译了此源代码

g++ -g print_dbg.cpp -o print_dbg

我要说的可能没有必要,但无论如何我都会这么做:请注意,my_obj在main()中被声明为局部变量。这意味着当我在这个范围内调试代码时,我只能访问方法publicPrint()。当代码执行跳到getchar()的开头时,代码执行将在另一个范围,即另一个堆栈帧,并且my_obj将不再存在于这个新上下文中。这只是一个提醒

在gdb上,如果在my_obj有效的地方设置断点,则可以通过:call my_obj.publicPrint() 执行方法publicPrint()

$ gdb print_dbg 
GNU gdb (GDB) 7.1-ubuntu
Copyright (C) 2010 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 "i486-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/karl/workspace/gdb/print_dbg...done.
(gdb) list main
12              }
13      };
14
15
16      int main()
17      {
18          aClass my_obj;
19
20          getchar();
21      }
(gdb) break main
Breakpoint 1 at 0x804871d: file print_dbg.cpp, line 20.
(gdb) run
Starting program: /home/karl/workspace/gdb/print_dbg 
Breakpoint 1, main () at print_dbg.cpp:20
20          getchar();
(gdb) call my_obj.publicPrint()
public method
(gdb)