如何为LLVM声明压缩结构(不填充)?
可以告诉GCC它不应该为结构使用填充。 这是使用__attribute__((packed))
。
typedef struct { uint8_t startSymbol; uint8_t packetType; uint32_t deviceId; uint16_t packetCRC; } PacketData __attribute__((packed));
但是,最新的Xcode使用LLVM并且无法识别该属性。 如何为LLVM定义压缩结构?
可以在此处找到问题的完整描述
更新我正在使用Xcode 4.5.1 for iOS,它使用Apple LLVM 4.1编译器。 我在上面的代码示例中的Xcode中收到“’packed’属性被忽略”警告。
你真的尝试过吗? 我只是在我的机器上测试它,并使用clang
编译__attribute__((packed))
。
编辑:我得到了相同的警告(“警告:打包属性未使用”)
typedef struct { int a; char c; } mystruct __attribute__((packed));
在这种情况下, sizeof(mystruct)
是8。
然而,
typedef struct __attribute__((packed)) { int a; char c; } mystruct;
工作得很好, sizeof(mystruct)
是5。
结论:似乎该属性需要在struct标签之前才能使其正常工作。
您可以使用预处理程序指令为结构指定字节对齐,因此编译器不会执行填充:
#pragma pack(1)
typedef struct{
char t1;
long long t2;
char t3;
}struct_size_test;
#pragma options align=reset
请参阅stackoverflow上此问题的答案。
Linux上的clang 3.5 –
typedef struct __attribute __((packed))thing1 {int blah; } THING_ONE;
工作。