当使用#pragma pack(1)时,我发现Solaris和Linux之间的结构大小不同。在Linux上,Derv的大小为128,但在Solaris上它的大小为132.有人可以告诉我为什么会这样吗?如何在Solaris上获得128?以下是代码:
#include <inttypes.h>
#include <iostream>
#include <stddef.h>
#pragma pack(1)
struct Base {
char m_1;
uint8_t m_2;
uint64_t m_3;
uint64_t m_4;
uint16_t m_5;
uint32_t m_6;
uint32_t m_7;
uint64_t m_8;
uint64_t m_9;
uint32_t m_10;
char m_11[6];
};
struct Derv : Base {
int m_1;
char m_2[66];
int m_3;
};
#pragma pack()
int main()
{
std::cout << sizeof(Base) << ", " << sizeof(Derv) << std::endl;
std::cout << offsetof(struct Derv, m_1)
<< ", " << offsetof(struct Derv, m_2)
<< ", " << offsetof(struct Derv, m_3)
<< std::endl;
}
编译如下: 在Linux上:g ++ -Wno-invalid-offsetof struct_test.cpp 在Solaris上:CC -g0 -xarch = sse2 -mt struct_test.cpp
版本:
$ g ++ -v
使用内置规格。 目标:x86_64-redhat-linux 配置为:../ configure --prefix = / usr --mandir = / usr / share / man --infodir = / usr / share / info --with-bugurl = http://bugzilla.redhat.com/bugzilla --enable-bootstrap - -enable-shared --enable-threads = posix --enable-checking = release --with-system-zlib --enable -__ cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable- languages = c,c ++,objc,obj-c ++,java,fortran,ada --enable-java-awt = gtk --disable-dssi --with-java-home = / usr / lib / jvm / java-1.5。 0-gcj-1.5.0.0 / jre --enable-libgcj-multifile --enable-java-maintainer-mode --with-ecj-jar = / usr / share / java / eclipse-ecj.jar --disable-libjava -multilib --with-ppl --with-cloog --with-tune = generic --with-arch_32 = i686 --build = x86_64-redhat-linux 线程模型:posix gcc版本4.4.7 20120313(Red Hat 4.4.7-3)(GCC)
Solaris编译器:
$ CC -V
CC:Sun C ++ 5.9 SunOS_i386 Patch 124864-13 2009/05/26
感谢您的时间。
答案 0 :(得分:2)
Sun C ++编译器对pragma的理解略有不同。您还需要将选项-misalign
传递给它,以便允许小于默认对齐。
有关详细信息,请参阅Sun Studio 12: C++ User's Guide。
答案 1 :(得分:1)
Pragma pack不保证没有空格;充其量它意味着编译器将尽可能多地打包东西。我的建议是将结构中的项目从最大到最小重新排序;虽然根据经验,不能保证(pragma,根据定义,依赖于实现),通常会消除结构包装中的“漏洞”。
您可以使用其他编译器标志,但如果您不关心结构中项目的顺序,则从大到小排序通常以更便携(-ish)的方式进行操作。 / p>
(显然这并不总是一个选择 - 例如,如果你试图填满一个通过线路或传递给某个API的结构。但它适用于内部存储)
答案 2 :(得分:0)
Oracle Solaris Studio 12.3 C编译器版本5.12
$ > man cc
...
-misalign
(SPARC) Obsolete. You should not use this option. Use
the -xmemalign=1i option instead. For a complete list
of obsolete options and flags, see the C User's Guide.
因此,在带有C编译器的Oracle Solaris Studio 12.3上,您应该使用
-xmemalign=1i
,而不是-misalign
另请参阅Oracle Solaris Studio 12.3:C用户指南:2.11.19 #pragma pack http://docs.oracle.com/cd/E24457_01/html/E21990/bjaby.html#indexterm-96