Using __attribute((packed))__ on picky architectures

Andrew Haley aph@redhat.com
Sat Jan 17 17:59:00 GMT 2009


Baurzhan Ismagulov wrote:
> On Fri, Jan 16, 2009 at 06:57:57PM +0000, Andrew Haley wrote:
>> That's right.  The important thing to realize is that the type of &field2
>> in
>>
>> 	struct test
>> 	{
>>     	    UINT8  field1;
>>     	    UINT16 field2;
>>     	    UINT8  field3;
>> 	} __attribute__((__packed__));
>>
>> is not UINT16 *; the compiler knows that it's an element of a packed
>> struct, and generates code accordingly.  The correct procedure is always
>> to pass the address of the whole struct.
> 
> I've recently had the need to handle a non-aligned struct member from
> two different structures in a somewhat lengthy function. So, two
> questions:
> 
> * Is there anything against implementing packed function arguments (like
>   void handle(UINT16 *data __attribute__((packed)))) in gcc? Not that
>   I'm going to do that right now :) , but in principle?

> * The recommended practice in such cases is to parse the data char by
>   char. OTOH, portably casting a struct over a legacy protocol data or
>   binary file would save much effort. C99 flexible array members, for
>   example, do help. So, why isn't alignment (or, to be more exact,
>   packed structures) standardized? Is it "just" difficulty of finding
>   "the common denominator" for all platforms out there, or are there any
>   more fundamental issues?

It's very fundamental.  If you've read the ISO C standard you'll have
noticed that there are very few requirements for memory layout of data.
struct members have to appear in memory in the order they were declared,
and a pointer to a struct, suitably converted, points to its initial
member, but that's about it.

Standardizing memory layout in a way that would be meaningful across
the wide range of machines that C supports would be difficult, and I
suspect the result wouldn't please anyone.

The language that the gcc uses to define 'packed' is much too weak
to be used in a standard.  I suspect if it were firmed up enough to
be submitted a lot of problems would become apparent.

Andrew.



More information about the Gcc-help mailing list