delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1996/10/25/21:38:38

From: ovek AT arcticnet DOT no (Ove Kåven)
Newsgroups: comp.os.msdos.djgpp
Subject: __attribute__((packed))
Date: Sun, 20 Oct 1996 13:26:43 GMT
Organization: Vplan Programvare AS
Lines: 58
Message-ID: <54h664$kgf@troll.powertech.no>
NNTP-Posting-Host: alwayscold.darkness.arcticnet.no
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Well I was getting bored of all those posts incorrectly stating that
you have to use the packed attribute on each and every member of a
structure if you want it packed, when I had for a long time used what
it says in the Info documentation ("Type Attributes"):

>Specifying this attribute for `struct' and `union' types is
>equivalent to specifying the `packed' attribute on each of the
>structure or union members.

And even successfully wrapped it into a typedef... so I decided to
write a test program that demonstrated this:

#include <stdio.h>

typedef struct {
 char A;
 int B;
} S1;

typedef struct {
 char A __attribute__((packed));
 int B __attribute__((packed));
} S2;

typedef struct {
 char A;
 int B;
} __attribute__((packed)) S3;

typedef unsigned p;

int main()
{
 S1 s1;
 S2 s2;
 S3 s3;
 
 printf("S1: Offset to B is %d, size is %ld\n",
  (p)(&s1.B)-(p)(&s1),sizeof(s1));
 printf("S2: Offset to B is %d, size is %ld\n",
  (p)(&s2.B)-(p)(&s2),sizeof(s2));
 printf("S3: Offset to B is %d, size is %ld\n",
  (p)(&s3.B)-(p)(&s3),sizeof(s3));
 return(0);
}

And the output is, indeed,
S1: Offset to B is 4, size is 8
S2: Offset to B is 1, size is 5
S3: Offset to B is 1, size is 5

Maybe some of this confusion might be caused by the fact that the
pointer "(See the "Type Attributes" section of the "GNU C/C++
Manual")" in section 22.9 of the FAQ on www.delorie.com really links
to "Variable Attributes" instead, which has an packed-attribute
example in the fashion of S2 in my test program.


- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019