How to make my compiler stop padding structs

Recommended Posts

I just wrote a BMP loader from scratch that didn't use any structs. The first 14 bytes of a bmp file are:
byte# - variable name
2  	bfType
4  	bfSize
2  	bfReserved1
2  	bfReserved2
4  	bfOffBits

I had to use auto variables because whenever I would create a struct (Called BitmapFileHeader) that SHOULD be 14 bytes, mingw would pad it to 16 bytes. When I loaded it from the file stream, I would get improper values, and saving it was wrong too (of course). What I want to know is how I can get MinGw to stop padding my structs out. It's no big deal because the loader I just wrote works perfectly, but it's a lot more convenient to be able to use structs. Thanks for any help.

Share on other sites
In mingw (and also GCC) you can do like this:
#pragma pack(push, 1)struct BitmapFileHeader{  /* struct members go here */};#pragma pack(pop)

But be aware that this can have impact on speed as 32bits processors are accessing memory at 4bytes boundaries. I would suggest loading every member individually.

Also note that this will only work on mingw and GCC, Microsoft Visual C++ uses another directive to pack structs.

If i remember correctly, there should be a struct in windows.h for bitmap files headers but don't remember the name, a quick google should give you the answer.

Hope that helps !
Matt

Share on other sites
well yeah there IS a bitmap struct, but I don't want to use it 'cause I like doing stuff like this :) Anyway, thanks for the #pragma command. Rating++ (oops, already rated you up I think)
Oh, and I'll probably end up loading the stuff individually, but when I'm still hacking around I like the convenient solution.
Thanks man!

Share on other sites
14%4 is non zero. Is saving two measly bytes worth reading unaligned data?

Never mind, this is for loading from a file. Well, endianness and word sizes will still bork it up. Hooray.

Share on other sites
I'm already compensating for Big and Little endianness in my PutPixel function and word sizes haven't been a problem, so I think I'm okay.

Share on other sites
Quote:
 Original post by lemurionAlso note that this will only work on mingw and GCC, Microsoft Visual C++ uses another directive to pack structs.

According to this, Microsoft also supports it as extended syntax.

Another method of doing this in GCC is __attribute__((packed)), which is what I've been using so far. However, lemurion's approach appears to be compatible with both GCC and MSVC, so I'll be switching over.

Share on other sites
Note that you don't have to use "auto variables" (I assume that you specifically mean separate auto vars for each value) in order to read the values individually; you can keep them wrapped in a struct, and just read in to structInstance.fieldName . :)

Create an account

Register a new account

• Forum Statistics

• Total Topics
628284
• Total Posts
2981831

• 10
• 10
• 10
• 11
• 17