结构填充编译标志 [英] structure padding compile flag
问题描述
typedef struct{
char t1;
long long t2;
char t3;
}struct_size_test;
printf("sizeof(long long)==[%ld]\n", sizeof(long long));
printf("sizeof(char)==[%ld]\n", sizeof(char));
printf("sizeof(struct_size_test)==[%ld]\n", sizeof(struct_size_test));
在iOS和OS X gcc中struct_size_test的结果不同。
在iOS中的结果是
The result of struct_size_test in iOS and in OS X gcc is different.
The result in iOS is
sizeof(long long)==[8]
sizeof(char)==[1]
sizeof(struct_size_test)==[24]
gcc is
sizeof(long long)==[8]
sizeof(char)==[1]
sizeof(struct_size_test)==[16]
我googled这个,添加-malign-double作为gcc编译标志。
但它显示
I googled this and found some advice that to add "-malign-double" as the gcc compile flag. But it shows
clang: error: unknown argument: '-malign-double' [-Wunused-command-line-argument-hard-error-in-future]
clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
任何想法如何同步iOS和OS X的结构填充?
非常感谢!
Any idea how to sync the structure padding for iOS and OS X? Thanks a lot!
推荐答案
我认为答案应该是你绝对不想这样做。
I think the answer should be that you most certainly don't want to do this.
您可以尝试nneonneo的解决方案或添加 __属性__((packed))
到您的结构,相同大小的OS X和iOS,但记住这是一个编译器特定的功能,将使你的代码更少便携
You could try nneonneo's solution or add __attribute__((packed))
to your structs to make the structs the same size on both OS X and iOS but keep in mind this is a compiler specific feature and will make your code less portable
此外,如果你改变了填充,你的程序可能会崩溃或运行效率较低的架构(特别是iOS / ARM)由于对齐要求不符合。有些ARM架构(不确定iDevices)不允许未对齐的读/写操作,如果不运行速度更慢,会直接崩溃(因为需要两次内存读取,而不是一次)。
Furthermore, if you did change the padding, your program would likely crash or run less efficiently on either architectures (especially iOS/ARM) due to alignment requirements not being met. Some ARM architectures (unsure about iDevices) won't allow unaligned reads/writes and will outright crash if not run slower (since two memory reads are required instead of one).
解决方法可能是使用最高的公共对齐方式(显示为8),这只需要更多的空间。
A workaround might be to use the highest common alignment (appears to be 8), which would simply take a bit more space. But this is still hacky and non-portable.
此外,为什么要这样做呢?
Why are you trying to do this anyway?
:nneonneo的答案应该看起来像这样:
nneonneo's answer probably should look like this:
typedef struct{
char t1 __attribute__ ((aligned (8)));
long long t2 __attribute__ ((aligned (8)));
char t3 __attribute__ ((aligned (8)));
} struct_size_test;
这篇关于结构填充编译标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!