offsetof at compile time

匆匆过客 提交于 2019-11-27 02:22:31

问题


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

回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/1379298/offsetof-at-compile-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!