From: "John M. Aldrich" Newsgroups: comp.os.msdos.djgpp Subject: Re: Problem with Packed structs Date: Mon, 07 Apr 1997 11:52:18 -0700 Organization: Two pounds of chaos and a pinch of salt Lines: 57 Message-ID: <33494262.611B@cs.com> References: <19970407 DOT 211716 DOT 7135 DOT 3 DOT fwec AT juno DOT com> Reply-To: fighteer AT cs DOT com NNTP-Posting-Host: ppp108.cs.com Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Mark T Logan wrote: > > Since DJGPP packs structs, the structs are of a different size than you > might find when using a 16 bit compiler. You can't read the file in unless > the structs that you are reading into are the same as the structs that were > written. > > What if I want to read a file I make with say, a Visual Basic 16 bit > program? Your terminology is backwards. DJGPP _aligns_ struct fields, padding them with sufficient space to align them on 4 byte boundaries. It also adds padding to the end of each structure. In order to prevent it from doing this, you must use the following syntax: struct foo { char bar __attribute__((packed)); short baz __attribute__((packed)); long xyz[3] __attribute__((packed)); }; Without packing, this struct would be (1 + 3) + (2 + 2) + (4 * 3 + 0) = 20 bytes. With packing, it becomes 15 bytes, which is the same as it would be under Turbo C. Note that as long as you're using C and not C++, it is sufficient to append the __attribute__((packed)) to the end of the struct definition, like so: struct foo { char bar; short baz; long xyz[3]; } __attribute__((packed)); Due to a bug in GCC, this syntax does not work when compiling C++ programs. You should also be aware that DJGPP uses 4 byte integers, not the 2 byte integers that you are probably used to. Therefore, if you want to read 2 byte integers, you must declare the struct field as 'short'. In fact, for portable code you should never use 'int', only 'short' and 'long'. BTW, the FAQ goes into great detail on the reasons for alignment and packing in chapters 22.9 and 22.10. -- John M. Aldrich * Anything that happens, happens. * Anything that, in happening, causes something else to happen, causes something else to happen. * Anything that, in happening, causes itself to happen again, happens again. * It doesn't necessarily do it in chronological order, though. --- Douglas Adams