C++中__attribute__((packed))不能使用
来源:互联网 发布:java rs232串口通信 编辑:程序博客网 时间:2024/06/02 07:29
__attribute__((packed))
这个在C语言中,用来配置struct内存的编译器预处理指令,相信大家并不陌生。典型的应用,我给你举个小栗子试试。
1. struct example12. {3. char c;4. char d;5. int e; 6. };7. int main(int argc, char* argv[]) 8. {9. printf("size of example1 is %d.",sizeof(example1));10.return 0;11. }
程序输出为
size of example1 is 12.
因为默认情况下,struct的内存分配会以最大内存为标准,把所有类型都赋予那么大的内存,比如上例中char类型,默认也被分配为了int类型的4个字节。
那么,如果希望每种类型都按本身的内存大小分配空间该怎么办呢?
在C语言中,可以采用__attribute__((packed))
使用方法再举个栗子
1.struct example12. {3. char c;4. char d;5. int e; 6. } __attribute__((packed));7. int main(int argc, char* argv[]) 8. {9. printf("size of example1 is %d.",sizeof(example1));10.return 0;11. }
要注意的是:1、attribute前后为两个下划线,括号直接跟着最后一个下划线,第一个下划线前面有空格。2、attribute还有很多其他的属性,不一而足。
好了正题来了,你要是也在C++里那么用,那么很有可能你根本运行不了,我改个C++的栗子:
1.struct example12. {3. char c;4. char d;5. int e; 6. } __attribute__((packed));7.int main(int argc, char* argv[])8. {9. std::cout << sizeof(example1) << endl;10. return 0;11. }
知道原因吗??其实只是前文中说的编译器预处理命令不同罢了。
这时候,能够解决该问题的办法,就是采用#pragma预处理命令,还是刚才的C++代码:
1.#pragma pack(1)2.struct example13. {4. char c;5. char d;6. int e; 7. } ;8.int main(int argc, char* argv[])9. {10. std::cout << sizeof(example1) << endl;11. return 0;12. }
输出结果是6
好了,你看用C++也可以不默认分配内存了吧?
0 0
- C++中__attribute__((packed))不能使用
- C Tips: __attribute__((packed))
- __attribute__((packed))使用介绍
- __attribute__ ((packed))
- __attribute__ ((packed))
- __attribute__ ((packed))
- __attribute__((packed))
- __attribute__((packed))
- __attribute__((packed))
- __attribute__ ((packed))
- __attribute__ ((packed))
- __attribute__((packed))
- __attribute__((packed))
- __attribute__ ((packed)) 的作用
- __attribute__ ((packed)) 的作用
- __attribute__ ((packed)) 的作用
- __attribute__ ((packed)) 的作用
- __attribute__ ((packed)) 的作用
- 从即日起记录我的程序猿之路,留住学习与生活中的点点滴滴
- [leetcode-48]Rotate Image(java)
- java中的集合
- OpenGL ES 颜色缓冲 深度测试 表面剔除
- iOS多线程编程之NSThread的使用
- C++中__attribute__((packed))不能使用
- Day8.02
- Eclipse出现An error has occurred问题解决方案
- siva理论在网络营销中的案例分析
- UVa 11081 - Strings(dp)
- hdu 4902 Nice boat (线段树)
- 开源机器学习工具scikit-learn入门
- Fewest Flops
- iOS学习笔记5-GCDAsyncUdpSocket中的dispatch_queue_set_specific