Article 6J3Y5 Struct size issue - Tell C++ not to add bytes to a struct

Struct size issue - Tell C++ not to add bytes to a struct

by
vmelkon
from LinuxQuestions.org on (#6J3Y5)
Hello,
I have my own BMP file reader. It is written in C++.
I am compiling it for Linux, using Qt Creator so underneath it, I think it uses gcc.

So, I think it is only natural to have structure that englobe a set of data.
A lot of file formats use some kind of structure.

Code:struct BITMAPFILEHEADER
{
ushort bfType;
uint bfSize;
ushort bfReserved1;
ushort bfReserved2;
uint bfOffBits;
};

We tend to write the structure to file via something like
Code:BITMAPFILEHEADER BitmapFileHeader;
....
....
fwrite(&BitmapFileHeader, 1, sizeof(BITMAPFILEHEADER), hfile);BITMAPFILEHEADER should be 14 bytes but gcc has turned that into 16 bytes.
In other words, the BMP file created is not valid.

There is this:
https://en.cppreference.com/w/cpp/language/alignas

but I think that just effects start address. It helps with CPU optimization to have data start at certain addresses.

Is there something I can put in the C++ code to make it NOT ADD additional bytes to my struct?

It is possible to do it with compiler flags but I would prefer to do it in the C++ code.

That sort of code is very common for writing/reading a file, for sending some data over a network.
If the compiler does whatever it wants, then it can break your code.
External Content
Source RSS or Atom Feed
Feed Location https://feeds.feedburner.com/linuxquestions/latest
Feed Title LinuxQuestions.org
Feed Link https://www.linuxquestions.org/questions/
Reply 0 comments