In windows you can include the windows.h header file when trying to parse bmp files and the dataTypes WORD and DWORD are predefined for you (from what I have read). In linux, I need to use these dataTypes, but I do not know how to define them and cannot include the windows.h header. How do I go about doing this in C++?
Share
Include
<stdint.h>, and then you can portably replaceWORDwithuint16_tandDWORDwithuint32_t. AndBYTEwithuint8_t, of course:If you want you can add the following code:
But beware! If you want to be portable, you must have in mind the endianness of the multi-byte values. Microsoft code almost always assume little-endian, but Linux can be run in both little and big-endian machines.
UPDATE:
Your new problem you talk about in the comments about the
BITMAPFILEHEADERis not related to the type of the fields but to the packing of the struct: the compiler may add padding bytes between fields in the struct in order to satisfy alignment (or other requirements).Microsoft compilers align integer type to an address multiple of its size. That is,
WORDandSHORTvalues are aligned to an address multiple of 2, andDWORDandLONGvalues to multiple of 4.If you see the definition of your struct:
Note that the
bfSizefield is sized 4 bytes, so it will be aligned to a multiple of 4. Instead of being in offset 2 of the struct, it will be in offset 4, adding 2 padding bytes.Now, all Windows headers all compiled with the option
#pragma packthat tells the compiler to ignore the alignment restrictions in struct fields. So the former struct is actually:The GCC compiler supports the
#pragma packonly as a compatibility with MS compilers, and only with x86 compilers.If you want to go fully portable you should read the struct directly, but read the bytes as a stream and build the values one by one (read 2 bytes into
bfType, read 4 bytes intobfSize, etc.)If you want to go portable to other Linux you can use the GCC pragma (but beware of the endiannes):