offsetof at compile time

谁说我不能喝 提交于 2019-11-28 08:40:55

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.

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.

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.

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