Full disclosure - this is homework, although completed and fully working, I'm searching for a nicer solution.
I have a binary file, which was created by a program compiled within Visual Studio (I believe). The structure looks somethin开发者_StackOverflow中文版g like this.
struct Record { char c; double d; time_t t; };
The size of this structure on Windows with Visual Studio 2008 gives 24 bytes. 1 + 8 + 8 = 24
. So there's some padding going on. The same structure on Linux and gcc gives 16 bytes. 1 + 8 + 4 = 16
. To line this up I added some padding and changed time_t
to another type. So then my struct looks like this.
struct Record { char c; char __padding[7]; double d; long long t; };
This now works and gcc gives its size as 24 bytes, but it seems a little dirty. So two questions..
Why is this implemented differently between the two compilers?
Are there any __attribute__ ((aligned))
-type options or any other cleaner solutions for this?
The difference stems from whether we 32bit align doubles by default or 64bit align doubles by default. On a 32 bit machine, having a double on a 64 bit boundary may have some benefits but is probably not huge. VC is then probably more careful about this than gcc.
The botton line is that if you are using structs for serialization you should ALWAYS make them packed (ie 8 bit aligned) and then do the alignment by hand. This way your code is sure to be compatible across platforms.
精彩评论