有没有一种方法来确定一个成员在​​编译时偏移? [英] Is there a way to determine a member offset at compile time?

查看:91
本文介绍了有没有一种方法来确定一个成员在​​编译时偏移?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现我花了很多时间试图确定结构成员偏移,同时调试。我在想,如果有一个快速的方法来确定在编译时一个大的结构中成员的偏移量。 (注:我知道创建编译时断言,一个偏移量是在给定范围内的几种方法,我可以做的正确值二进制搜索,但我正在寻找的东西更有效)。我使用的是一个相当新的 GCC 的版本编译的 C 的code。

I'm finding I'm spending a lot of time trying to determine member offsets of structures while debugging. I was wondering if there was a quick way to determine the offset of a member within a large structure at compile time. (Note: I know several ways of creating compile time assertions that an offset is in a given range, and I can do a binary search for the correct value, but I'm looking for something more efficient). I'm using a fairly recent version of gcc to compile C code.

推荐答案

好吧,这里回答我的问题:注:我期待以确定偏移的编译时间的,就是我不想必须运行code(我也可以编译正是我所需要的文件,而不是整个系统):下面可以剪切和粘贴那些有兴趣谁:

Ok, answering my own question here: Note: I'm looking to determine the offset at compile time, that is, I don't want to have to run the code (I can also compile just the files I need, and not the whole system): The following can be cut and paste for those who are interested:

#include <stddef.h>

#define offsetof_ct(structname, membername) \
void ___offset_##membername ## ___(void) { \
        volatile char dummy[10000 + offsetof(structname, membername) ]; \
        dummy[0]=dummy[0]; \
}

struct x {
        int a[100];
        int b[20];
        int c[30];
};

offsetof_ct(struct x,a);
offsetof_ct(struct x,b);
offsetof_ct(struct x,c);

然后运行:

~/tmp> gcc tst.c -Wframe-larger-than=1000
tst.c: In function ‘___offset_a___’:
tst.c:16:1: warning: the frame size of 10000 bytes is larger than 1000 bytes
tst.c: In function ‘___offset_b___’:
tst.c:17:1: warning: the frame size of 10400 bytes is larger than 1000 bytes
tst.c: In function ‘___offset_c___’:
tst.c:18:1: warning: the frame size of 10480 bytes is larger than 1000 bytes
/usr/lib/gcc/x86_64-redhat-linux/4.5.1/../../../../lib64/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: ld returned 1 exit status

我然后减去10000得到的偏移量。注:我尝试添加的#pragma GCC诊断警告-Wframe-较大比= 1000到文件,但它不喜欢它,所以它必须要在命令行上指定的。

I then subtract 10000 to get the offset. Note: I tried adding #pragma GCC diagnostic warning "-Wframe-larger-than=1000" into the file, but it didn't like it, so it'll have to be specified on the command line.

约翰

这篇关于有没有一种方法来确定一个成员在​​编译时偏移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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