TCLUG Archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [TCLUG:9042] Struct Packing



On Oct 08, 1999, "John R. Sheets" <dusk@ravendusk.org> wrote:
> Hey, does anyone know how to turn off struct-padding in gcc?  By
> default, it aligns struct fields at 4-byte intervals, but I'm trying to
> read a binary file directly into a struct with 1-byte packing (i.e. with
> no padding).
> 
> I've tried -fpack-struct and "#pragma align 1", to no avail (although it
> seems like I might have gotten it to work once, somehow, but I don't
> know how).  Any other options?  As I understand, -fpack-struct _should_
> be doing the job.  Can't figure out why not.

FYI, I think I figured it out...

This turns out to be a bug in gcc.  When compiling C code, it
works as it should, but when compiling C++ code, it happily ignores the
packing instructions.  Argh!  That's why it worked on me that one time.

The workaround (no guarantees on portability) is to use the
__attribute__((packed)) specifier to force packing on individual
structs, which is probably a safer way to go anyway.  Does anyone know
anything about __attribute__?  I'd never seen it before.  

Anyway, if you're really curious, here's how ya do it:

struct __attribute__((packed)) mystruct
{
  ...
};

Kinda ugly...oh well.

John