我有一个带有printDebug方法的类.它没有在代码中的任何地方使用,但我想在使用gdb(使用调用)进行调试时使用它.这基本上是以一种格式良好的方式打印对象的内容,例如我可能有一组集合.用于此的g ++选项是什么?我试过-O0但这不起作用.
我使用的工作是在构造函数中对debugPrint进行伪调用,并提供一个bool来指示你是否真的要打印或什么都不做.这很好,但必须有一个更好的方法来做到这一点.
如果我理解正确--O0不应该做任何优化,所以不应该删除死代码,但也许我错了.
kar*_*lip 18
如果你有一个方法没有在代码的任何地方使用gcc智能功能可以识别这个并在编译你的应用程序时忽略它.这就是为什么当您显示方法未在结果上显示的应用程序的符号(使用nm)时.
但是,如果要强制编译该方法,则需要在方法声明中指定_ attribute _ 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 }
Run Code Online (Sandbox Code Playgroud)
出于测试目的,我编译了这个源代码-g:
g++ -g print_dbg.cpp -o print_dbg
Run Code Online (Sandbox Code Playgroud)
我要说的可能是不必要的,但无论如何我都会这样做:注意my_obj在main()中声明为局部变量.这意味着我publicPrint()在调试此范围内的代码时只能访问该方法.当代码执行跳转到getchar()的开头时,代码执行将在另一个范围,即另一个堆栈帧,并且my_obj将不再存在于此新上下文中.这只是一个抬头.
在gdb上,如果设置了一个my_obj有效的断点,你可以publicPrint()通过以下方式执行该方法:call my_obj.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)
Run Code Online (Sandbox Code Playgroud)