使用gdb调用printDebug方法
Use gdb to call a printDebug method
我有一个带有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)
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 没有为自己的结构调用列表推回方法
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 枚举环境变量的惯用C++14/C++17方法
- 使用gdb调用printDebug方法