如何在GDB中定义offsetof()宏 [英] How to define offsetof() macro in GDB

查看:255
本文介绍了如何在GDB中定义offsetof()宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了方便起见,我想在GDB中定义一些辅助marcos,其中之一是offsetof()宏.

I want to define some auxiliary marcos in GDB for convenience, one of them is the offsetof() macro.

我尝试过

define offsetof
    if $argc == 2
        (int)(&((($arg0 *)0)->$arg1))
    end
end

它不起作用是因为:

  1. 诸如struct node之类的类型将分为Structnode,因此$arg0 = Struct$arg1 = node.
  2. 我不确定gdb的命令是否可以返回值.
  1. A type such as struct node will be splitted into Struct and node, so $arg0 = Struct, $arg1 = node.
  2. I am not sure if gdb's command can return a value.

有人可以帮我吗?

推荐答案

我认为将其定义为函数比将offsetof定义为命令要好.这样,您就可以在表达式中使用它了;如果您只想查看偏移量,则始终可以使用print.

Rather than define offsetof as a command, I think it's better to define it as a function. That way you can use it in expressions; and if you just want to see the offset you can always just use print.

有两种方法将offsetof定义为函数.

There are two ways to define offsetof as a function.

如果您要调试C或C ++,则可以简单地将其定义为宏:

If you are debugging C or C++, you can simply define it as a macro:

(gdb) macro define offsetof(t, f) &((t *) 0)->f

所以给定了:

struct x {
  int a;
  long b;
};

在我的机器上,我得到:

On my machine I get:

(gdb) p offsetof(struct x, a)
$1 = (int *) 0x0
(gdb) p offsetof(struct x, b)
$2 = (long *) 0x8

上述"C或C ++"限制的原因是其他语言不会通过gdb的内置预处理器运行其表达式.

The reason for the "C or C++" restriction above is that other languages don't run their expressions through gdb's built-in preprocessor.

如果您希望它以其他语言运行,那么答案是用Python编写一个新的便捷函数.这涉及更多,但是请参见gdb.Function的gdb文档.

If you want it to work in other languages, then the answer is to write a new convenience function in Python. This is a bit more involved, but see the gdb documentation for gdb.Function.

这篇关于如何在GDB中定义offsetof()宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆