在公司实习的时候,看到了这个属性的应用,做个总结:
其实很简单:程序中没有__attribute__(packed),优化对齐,一般是4字节对齐,有的话,紧凑型,不对齐,是多少就是多少。上代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17#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=%dn",sizeof(char)); printf("size of int=%dn",sizeof(int)); printf("size of unpacked_str=%dn",sizeof(struct unpacked_str)); printf("size of packed_str=%dn",sizeof(struct packed_str)); }
在codeblocks 17.12中运行结果如下:
但结果差强人意,第二个应该是5的,不知道是不是和编译器有关,这是我用的编译器。
是不是编译器的问题还需要确认,如果后续我得到了正确答案,我会更博的。
最后
以上就是隐形牛排最近收集整理的关于C语言__attribute__(packed)属性的全部内容,更多相关C语言__attribute__(packed)属性内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复