请问怎样在预编译的时候判断某个结构体的大小是否符合要求呢?

zhangxxdd 2006-10-12 05:30:35
比如这样:
typedef struct _MyType {
uint16_t t16;
uint32_t t32;
} MyType;
#define MyType_Size sizeof(MyType)
#if MyType_Size!=6
#error MyType is error!
#endif
//////////////////
可在编译的时候报错,指向的是 #if MyType_Size!=6 这一句, 报错信息为 missing binary operator before token "("
如果我把 #define MyType_Size sizeof(MyType) 改为 #define MyType_Size 8
这样在预编译的时候会提示 MyType is error!
//////////////////
我的需求就是,需要保证MyType的大小为6字节,请问应该怎样实现呢?谢谢指点一二了 :-)
...全文
855 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhangxxdd 2006-10-13
  • 打赏
  • 举报
回复
上面是c++的实现?晕掉,结贴了,谢谢各位先 :)
wingfiring 2006-10-12
  • 打赏
  • 举报
回复
预编译的时候是不可能啦,但是编译的时候还是可能的:
google 一下static_assert,boost和loki都有简单的实现,正好我手头上也有一个:
namespace cs
{
template<bool> struct compile_time_error{};
template<> struct compile_time_error<true>
{
typedef int static_assert_failed;
};
}
/** compile time error check*/
#define CS_STATIC_ASSERT(expr, msg) \
typedef compile_time_error<((expr) != 0)>::static_assert_failed ERROR_##msg

使用:
CS_STATIC_ASSERT(sizeof(MyType) == 6, MyType_is_error);

msg需要是合法的C++标志符,这个实现只在vc8上测试过.
飞哥 2006-10-12
  • 打赏
  • 举报
回复
长期关注,还没想通可能否
飞哥 2006-10-12
  • 打赏
  • 举报
回复
g++是不行了
首要的问题就是如果计算出struct大小,代替sizeof
我是搞不定了
zhangxxdd 2006-10-12
  • 打赏
  • 举报
回复
我用的是dev-c++,好像用的是gcc的编译器吧?
不知道我的需求还有另外的方法可以实现吗?谢谢了 :-)
飞哥 2006-10-12
  • 打赏
  • 举报
回复
我用G++去试试
飞哥 2006-10-12
  • 打赏
  • 举报
回复
是啊,sizeof不能在编译期获得

不知道lz用什么编译器
zhangxxdd 2006-10-12
  • 打赏
  • 举报
回复
谢谢楼上的,才回去看了下msdn,果然啊 :-(
The constant-expression is an integer constant expression with these additional restrictions:

Expressions must have integral type and can include only integer constants, character constants, and the defined operator.
The expression cannot use sizeof or a type-cast operator.
The target environment may not be able to represent all ranges of integers.
The translation represents type int the same as type long, and unsigned int the same as unsigned long.
The translator can translate character constants to a set of code values different from the set for the target environment. To determine the properties of the target environment, check values of macros from LIMITS.H in an application built for the target environment.
The expression must not perform any environmental inquiries and must remain insulated from implementation details on the target computer.

//////////////
在pascal里却又可以这样,
tBootControlSize=sizeof(tBootControl);
{$if tBootControlSize<>4} tBootControlSize size error {$ifend}
把pas改成c真晕啊 ~~~~~
飞哥 2006-10-12
  • 打赏
  • 举报
回复
#if #else #endif
里面不允许使用sizeof:(
这个是规定

70,020

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧