2008년 5월 7일 수요일

[스크랩] Structure packing with the GNU C Compiler

The GNU C compiler does not support the #pragma directives. In particular it does not support the "#pragma pack" directive. So when using the GNU C compiler, you can ensure structure packing in one of two ways

  • Define the structure appropriately so that it is intrinsically packed. This is hard to do and requires an understanding of how the compiler behaves with respect to alignment on the target machine. Also it is hard to maintain.
  • Use the "packed" attribute against the members of a structure. This attribute mechanism is an extension to the GNU C compiler. An example of how you would do this is below.
    	struct test
    {
    unsigned char field1 __attribute__((__packed__));
    unsigned short field2 __attribute__((__packed__));
    unsigned long field3 __attribute__((__packed__));
    } var1, var2;


    Note the use of the keyword "__attribute__" with the attribute "__packed__" within the double brackets (before the terminating semicolon of each member variable declaration).



    An alternate way of doing the above is as below.



    	struct test
    {
    unsigned char field1;
    unsigned short field2;
    unsigned long field3;
    } __attribute__((__packed__));

    typedef struct test test_t;

    test_t var1, var2;


    This will ensure that all members of the structure are packed. Note that this doesn't seem to work right if you try to combine the typedef and the struct definition or if you combine variable declarations with the structure definition.



댓글 없음: