xxxxx@imaginando.net wrote:
I have realized very recently that compilers in Windows have a different struct data alignment, and structure data padding.
What I have realized is that my main structure has different size when compiled in Windows then the size when compiled in Linux.
I think that is because in Linux, word size is 4 bytes and and in windows 8 bytes, please correct me if i’m wrong.
You’re wrong. There are rules in the language standards about packing,
and there are aspects that are implementation-dependent. In both cases
(Visual C++ and gcc), the actual packing depends on compiler
command-line parameters and pragmas. You probably have different
command-line settings and just don’t realize it.
What should I do to have a uniform structure data size across different operating systems?
You need to understand the rules. In general, if you set up your
structures so that you never include a misaligned data type, then this
problem never comes up. For example:
struct one {
unsigned char a1; // needs 1-byte alignment
unsigned char a2;
unsigned short a3; // needs 2-byte alignment, has 2-byte alignment
unsigned int a4; // needs 4-byte alignment, has 4-byte alignment
};
That structure will never have any padding. All of the types are
correctly aligned. But if a scramble the ordering, padding will be
inserted:
struct one {
unsigned char a1; // needs 1-byte alignment
unsigned short a3; // needs 2-byte alignment, so gets 1 byte padding
unsigned char a2;
unsigned int a4; // needs 4-byte alignment, so gets 3 bytes padding
};
You can override that requirement with the pragmas. If I use pragma
pack(1), then there will be no padding inserted.
There is one other thing that might be biting you. In 64-bit gcc,
“long” is a 64-bit type. In 64-bit Visual C++, “long” is a 32-bit type.
And it speaks about praga pack. I wonder if I should use a pragma pack of 1 byte to solve my problems.
We can’t answer that. If you have poorly thought out structures with
bad alignment, then “pragma pack” can hide those issues.
–
Tim Roberts, xxxxx@probo.com
Providenza & Boekelheide, Inc.