编译时的偏移量

8 c macros struct offsetof c-preprocessor

有没有办法在编译时找到结构成员的偏移量?我希望创建一个包含结构成员偏移量的常量.在下面的代码中,offsetof()宏在第一个printf语句中工作.但是,在第10行中使用声明会ofs生成错误:

"无法解析' - >'运算符作为常量表达式".

这样做还有其他办法吗?

struct MyStruct
{
   unsigned long lw;
   unsigned char c[5];
   int i;
   int j;
   unsigned long last;
};

const int ofs = offsetof(struct MyStruct, i);  // This line in error

int main(void)
{
   printf("Offset of c = %d.\n", offsetof(struct MyStruct, c) );
   printf("Offset of i = %d.\n", ofs );
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

Dev*_*lar 9

offsetof()宏一个编译时构造.没有符合标准的方法来定义它,但每个编译器都必须有一些方法来实现它.

一个例子是:

#define offsetof( type, member ) ( (size_t) &( ( (type *) 0 )->member ) )
Run Code Online (Sandbox Code Playgroud)

虽然技术上不是编译时构造(参见用户"litb"的注释),但每个编译器必须至少有一个这样的表达式,它能够在编译时解析,这正是offsetof()<stddef.h中定义的那样. >.

您的代码可能还有一些其他错误 - 缺少<stddef.h>的包含,或者其他一些令您厌烦的编译器.


War*_*ung 4

在我添加正确的 #includes 后,它会在没有警告的情况下使用 g++ 4 进行编译。

你是#include stddef.h吗?offsetof() 是一个宏,而不是 C 中的内置关键字。

如果这不能解决问题,请尝试使常量静态,以将其限制在模块中。这可能会让编译器高兴。