在KEIL C中编译出来怎么占一个字节

2019-08-05 18:13发布

union {
       struct {
          unsigned b0:1;
          unsigned b1:1;
          unsigned b2:1;
          unsigned b3:1;
          unsigned b4:1;
          unsigned b5:1;
          unsigned b6:1;
          unsigned b7:1;
          }oneBit;
         unsigned char allBits;
        } myFlag;
#define fast    myFlag.oneBit.b0
#define mid     myFlag.oneBit.b1
#define slow    myFlag.oneBit.b2
#define flow    myFlag.oneBit.b3
#define voice   myFlag.oneBit.b4
#define pause   myFlag.oneBit.b5
#define white   myFlag.oneBit.b6
#define on_off  myFlag.oneBit.b7
#define mark    myFlag.allBits
上面的语句在PICC中编译出来每一个占一个位,但在KEIL C中编译出来怎么占一个字节啊?如果在在KEIL C 中要实现如上功能,应该怎么写呢?
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
9条回答
wuhany
2019-08-05 22:38
这个不能怪Keil,是C标准规定了位域是2字节对齐的……也就是说就算你只定义了1bit的位域,它也要占用2字节,其它的15bit就这么空着……不信试一下以下代码:
typedef struct
{
         unsigned b0:1;
         unsigned b1:1;
         unsigned b2:1;
         unsigned b3:1;
         unsigned b4:1;
         unsigned b5:1;
         unsigned b6:1;
         unsigned b7:1;
}oneBitStructs;
typedef union
{
         oneBitStructs oneBit;
//        unsigned char allBits;
}myFlag;

myFlag flag;
void main(void)
{
         int size = sizeof(myFlag);
         size = sizeof(oneBitStructs);
         while(1)
                 ;
}
优化级别设为0
单步调试过程可以看到myFlag这个联合体占用了2字节,结构体oneBitStructs也是一样

一周热门 更多>