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.

 

grok2.gif (391 bytes) The latest version of this site has moved to it's own domain at http://www.grok2.com/. Please update your bookmarks and links. Click here to go to the new site.

 

-0-

The latest version of this site has moved to it's own domain at http://www.grok2.com/. Please update your bookmarks and links. Click here to go to the new site.

Other Stuff On This Site

Emacs for Vi Programmers
Installing Linux on Sony's Vaio PCG-Z505LE Laptop
Studying in New Zealand (July 2001 info)
Utilities for Programmers
Why is programming fun?
Mirror of Eric Pement's Sed FAQ
C Programming Language Links (Work in Progress)
Source Code Comprehension Tools
Structure packing with the GNU C compiler
Walt Disney World Photographs
PPP RFCs
FSM/HSM
Tcl/Tk GUI Application Rules

~0~

Tell me what you think!