关于__attribute__ ((packed))

来源:互联网 发布:粳米 知乎 编辑:程序博客网 时间:2024/05/05 17:32
#include <iostream>using namespace std;typedef struct{unsigned char ver;unsigned char cmd;unsigned short id;unsigned short retcode;}__attribute__ ((packed)) ACKPACK_CMD;struct my{char ch; int a;}__attribute__ ((packed));// 取消结构在编译过程中的优化对齐,按照实际占用字节数进行对齐struct my2{char ch; int a;};// 默认的字节对齐方式(4字节对齐, 不同编译器可能不同)int main(){cout << sizeof(ACKPACK_CMD) << endl;cout << sizeof(my) << endl;cout << sizeof(my2) << endl;return 0;}/*结论:1. 在win xp上运行结果为:6 5 8, 编译器为g++(cl.exe根本不认识packed)1. 在win7上运行结果为:6 8 8, 编译器为g++2. 在ubuntu上运行结果为:6 5 8, 编译器为g++说明:__attribute__ ((packed))的作用就是告诉编译器取消结构在编译过程中的优化对齐,按照实际占用字节数进行对齐,是GCC特有的语法。这个功能是跟操作系统没关系,跟编译器有关.*/

原创粉丝点击