offsetof at compile time

2019-01-17 23:58发布

Is there a way of finding the offset of a member of a structure at compile-time? I wish to create a constant containing the offset of a structure member. In the following code the offsetof() macro works in the first printf statement. However, the use in line 10 to declare ofs generates the error:

"Cannot resolve '->' operator as a constant expression".

Is there any other way of doing it?

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;
}

3条回答
2楼-- · 2019-01-18 00:38

The offsetof() macro is a compile-time construct. There is no standard-compliant way to define it, but every compiler must have some way of doing it.

One example would be:

#define offsetof( type, member ) ( (size_t) &( ( (type *) 0 )->member ) )

While not being a compile-time construct technically (see comments by user "litb"), every compiler must have at least one such expression that it is able to resolve at compile time, which is exactly what offsetof() is defined to in <stddef.h>.

There is probably some other error to your code - a missing include of <stddef.h>, or some other thing irritating your compiler.

查看更多
够拽才男人
3楼-- · 2019-01-18 00:40

If you have a #include <stddef.h> as I assume (the error message you cite without would be meaningless), it is a bug in your compiler. offsetof result is an integer constant expression in C99 as well as in C90.

查看更多
女痞
4楼-- · 2019-01-18 00:49

It compiles without warning here with g++ 4, after I add the proper #includes.

Are you #including stddef.h? offsetof() is a macro, not a built-in keyword in C.

If that doesn't fix it, try making the constant static, to confine it to the module. That might make the compiler happy.

查看更多
登录 后发表回答