offsetof在编译时 [英] offsetof at compile time

查看:195
本文介绍了offsetof在编译时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有找到在编译时的结构成员的偏移的一种方式?我想创建一个包含结构成员的偏移量的常数。在下面的code中的 offsetof()宏工作在第一的printf 语句。然而,在10号线使用申报 OFS 生成错误:


  

无法解析 - >运营商作为一个恒定的前pression。


有没有做任何其他方式?

 结构MYSTRUCT
{
   无符号长LW;
   unsigned char型C [5];
   INT I;
   诠释J;
   无符号长最后;
};const int的OFS = offsetof(结构MYSTRUCT,I); //此行错误INT主要(无效)
{
   的printf(偏移量c =%d个的\\ n,offsetof(结构MYSTRUCT,C));
   的printf(偏移我的=%d个\\ n,OFS);
   返回0;
}


解决方案

在offsetof()宏的的编译时间结构。没有定义它符合标准的方式,但每个编译器必须做的一些方法。

一个例子是:

 的#define offsetof(类型,成员)((为size_t)及(((键入*)0) - >成员))

虽然不是一个编译时构建的技术上的(见用户litb评论),每一个编译器必须至少拥有的有一个的这些非pression了它能够在编译时间来解决,这正是 offsetof()定义为上述< STDDEF.H方式>

有可能是一些其他错误您code - 缺失包括< STDDEF.H>中或其他一些事情刺激你的编译器

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

解决方案

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.

这篇关于offsetof在编译时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆