delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2003/03/18/22:45:03

Lines: 80
X-Admin: news AT aol DOT com
From: dang2015 AT aol DOT com (DanG2015)
Newsgroups: comp.os.msdos.djgpp
Date: 19 Mar 2003 03:31:07 GMT
Organization: AOL http://www.aol.com
Subject: "pragma pack" question
Message-ID: <20030318223107.25581.00000232@mb-dh.aol.com>
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

I've read conflicting information regarding the #pragma pack directive.
Unless I'm missing a compile option, it appears not to work to pad
struct elements to a known width.

As a side note, I read a post where someone said something such
as "padding hurts portability".  I think this is just the opposite;  If you
can control the size of structs, especially with binary I/O ACROSS
multiple platforms, you enhance portability, instead of being left at
the padding mercy of each machine (provided of course that your
data can be read on the most restrictive of the target machines...
a 32-bit int that uses all 32-bits most certainly cannot be read into
a 16-bit int regardless of padding;  however, a int that uses 16-bits
can be padded to 32 and will be readable on both 16-bit and 32-bit
machines).

In any case, I was surprised to see the output from this small test
program and was wondering if perhaps I'm doing something wrong.
If DJGPP (and other gcc's) don't support the #pragma pack( x )
directive, it surprises me that they would be silent about it and not
toss out a warning.

I threw in an obviously wrong pragma and the compiler rightfully
caught it:
     warning: ignoring #pragma foo
But it seemed quite happy with the pragma's in the code below;
it just didn't act on them.  Is there a compile option (I cannot find
one) that would enable the pragma's in the following code?

=============================================
#include <stdio.h>

#pragma pack (1)
struct A {
    char x;
    char y;
};

#pragma pack (2)
struct B {
    char x;
    char y;
};

#pragma pack (4)
struct C {
    char x;
    char y;
};

#pragma pack (8)
struct D {
    char x;
    char y;
};

int main( void ) {

    printf( "sizeof A = %d\n", sizeof(struct A) );
    printf( "sizeof B = %d\n", sizeof(struct B) );
    printf( "sizeof C = %d\n", sizeof(struct C) );
    printf( "sizeof D = %d\n", sizeof(struct D) );
    return 0;
}
=============================================

As I said, the output surprised me:

sizeof A = 2
sizeof B = 2
sizeof C = 2
sizeof D = 2

From what I've read, I can use the __attribute__ options to force memory
alignment which will probably have the desired effect, although I somehow
think that packing and actual boundary alignment can be different in some
cases [I need to sit and think about that though].

Any thoughts or help?

Dan

- Raw text -


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