Web www.grok2.com
grok2.gif (391 bytes)



Specific structure packing when using 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.


Site Links
  The Books I Own
  Main Page
  Vi in Emacs
  Linux on Vaio
  Study NZ
  Programming Fun?
  C Language
  Source Code Browsers
  C Struct Packing
  Walt Disney World
  Photographs of Flowers
  Random Photogaphs
  Put this on your site!
  The Sundial Bridge
  Repetitive Strain Injury (RSI)
  Selling Software Online (MicroISV)
  Tcl Tk Life-Savers
  The Experience Shows!
  Green Tips
  .htaccess tricks
  Web-Site Development Online Tools




Site copyright of domain owner. All rights reserved.