C语言__attribute__(packed)属性

在公司实习的时候,看到了这个属性的应用,做个总结:

其实很简单:程序中没有__attribute__(packed),优化对齐,一般是4字节对齐,的话,紧凑型,不对齐,是多少就是多少。上代码:

#include<stdio.h>
struct unpacked_str{
char c;
int x;
};
struct packed_str{
char c;
int x;
}__attribute__((packed));
int main()
{
    printf("size of char=%d\n",sizeof(char));
    printf("size of int=%d\n",sizeof(int));
    printf("size of unpacked_str=%d\n",sizeof(struct unpacked_str));
    printf("size of packed_str=%d\n",sizeof(struct packed_str));
}

在codeblocks 17.12中运行结果如下:

但结果差强人意,第二个应该是5的,这个适合编译器有关,这是我用的编译器。

不管可能是我这个编译器的问题,但是需要知道这么回事,如果后续我得到了正确答案,我会更博的。

猜你喜欢

转载自blog.csdn.net/salmonwilliam/article/details/81229160