歌词雨还在下滴滴答答:C 语言中 __packed

来源:百度文库 编辑:中财网 时间:2024/04/27 22:08:40

关键字: __packed ,C语言,内存对齐

【正文】

简单的说,__packed 用于表示C语言中结构的压缩,即:没有填充和对齐。

定义如下:

__packed struct P { ... };
struct P pp;    /* pp is a packed struct */

__packed也可以定义为:

struct my_unpacked_struct  {    char c;    int i;  } __attribute__ ((__packed__));  

如果一个结构体定义为 __packed,那么其子结构体也必须为__packed(如果有的话)例如:

struct S {...};
__packed struct P {...};
   
struct T {
    struct S ss; /* OK */
    struct P pp; /* OK */
};    
__packed struct Q {
    struct S ss; /* faulted - sub-structs must be packed */
    struct P pp; /* OK */
};

__packed struct P { char c; int x; };
__packed struct {
    struct P X;
    char z;
    struct P Y;
}Q;

此时,Q的内存映像如下:

          <-------------------- Q -------------------->   
          <-------- X -------->   <-------- Y -------->
          +---+---+---+---+---+---+---+---+---+---+---+
    byte  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10|
          | c | ------x------ | z | c | ------x------ |
          +---+---+---+---+---+---+---+---+---+---+---+

参考文献:

[1] http://www.iyonix.com/tools/packed.shtml

[2] http://axelio.wordpress.com/2007/07/24/be-careful-with-packed-structures/

[3] http://sig9.com/articles/gcc-packed-structures

[4] http://en.wikipedia.org/wiki/Data_structure_alignment