Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

c - offsetof at compile time

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.
", offsetof(struct MyStruct, c) );
   printf("Offset of i = %d.
", ofs );
   return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...