结构尺寸,其中包含位域是不同的编译器不同 [英] Size of structure which contains bitfields is different on different compiler

查看:174
本文介绍了结构尺寸,其中包含位域是不同的编译器不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我跑到下面的程序上的VS和海湾合作委员会。

I ran the below program on VS and on GCC.

#include <stdio.h>

int main(void)
{
    struct bitfield
    {
        unsigned a : 3;
        char b;
        unsigned c : 5;
        int d;
    }bit;

    printf("Size = %d\n", sizeof(bit));

    return 0;
}

要我吃惊的是,VS给出16作为的sizeof 结构和GCC给出了12。

To my surprise, VS gives 16 as the sizeof structure and GCC gives 12.

我的理解是,编译器会尝试分配 A 字符b Ç 为1行(存储区0,存储区1,池Bank2,区块3)和 INTð另一行。这似乎表明,该结构的大小应为8个字节(假定32位系统)。

My understanding is that the compiler tries to allocate a, char b and c in 1 row (Bank0, Bank1, Bank2, Bank3) and the int d in another row. This seems to suggest that the size of the structure should be 8 bytes (Assuming 32bit system).

任何人能解释这些结果?我运行在64位机器上。

Can anyone explain these results? I am running on a 64-bit machine.

推荐答案

编译器仅需要包被在结构中到相同的可寻址存储单元(这是可能的32比特的组块宣布相邻比特字段在这种情况下,给定的32位CPU)。你表现出它们之间的字符,所以编译器是免费的,因为它为所欲为分配你的结构。

The compiler is only required to pack bit fields that are declared adjacently in the struct into the same "addressable storage unit" (which is probably a chunk of 32 bits in this case, given 32 bit CPU). You showed a char in between them, so the compiler is free to allocate your struct as it pleases.

通常情况下,位字段难以置信的标准,因此完全非便携式和未predictable规定甚少。未指定的位分配的顺序。它没有被指定哪个位即最高位。未指定对齐。如果该位字段可能或可能不会跨越一个存储单元,它没有被指定。等等。

Generally, bit fields are incredibly poorly specified by the standard and therefore completely non-portable and unpredictable. The order of allocation of bits is not specified. It is not specified which bit that is the MSB. Alignment is not specified. It is not specified if the bit fields may or may not "straddle" a "storage unit". And so on.

此外,结构可以包含填充字节的任何地方。

Furthermore, a struct may contain padding bytes anywhere.

有一个更好的主意是从来没有使用位字段在所有,但使用位运算符来代替。

A better idea is to never use bit fields at all, but to use the bitwise operators instead.

这篇关于结构尺寸,其中包含位域是不同的编译器不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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