gcc (GCC) 4.7.0
c89
x86_64
你好,
我想知道在结构上使用 __attribute__ ((__packed__))
是否值得。在我看来,有了它,结构的尺寸会更小。通过我在下面进行的测试。所以使用它在尺寸上会有优势。
不使用它的情况,因为它不能跨其他编译器移植。所以对于 visual studio C++,这是行不通的。还有其他编译器。
编译器不优化代码吗?所以真的让编译器来决定做什么对性能更好吗?
使用对齐属性会有什么不同吗? __attribute__((packed, aligned(4)))
当我添加它返回 12 的大小时。
非常感谢您的任何建议,
#include <stdio.h>
struct padded {
int age; /* 4 */
char initial; /* 1 + 3 padded bytes */
int weight; /* 4 --> total = 12 */
};
struct __attribute__ ((__packed__)) unpadded {
int age; /* 4 */
char initial; /* 1 */
int weight; /* 4 --> total = 9 */
};
int main(int argc, char **argv)
{
struct padded padded_test;
struct unpadded unpadded_test;
printf("Padded [ %ld ]\n", sizeof(struct padded));
printf("Unpadded [ %ld ]\n", sizeof(struct unpadded));
return 0;
}
最佳答案
未对齐的内存访问在某些架构(例如 ia64、sparc64)上可能会非常慢。 __attribute__((__packed__))
主要用于您通过线路发送数据并希望确定布局的地方;不值得尝试使用它来节省内存空间。
如果您正在考虑使用__attribute__((__packed__))
进行有线传输,请三思;它不处理字节顺序,而且是非标准的。自己编写编码代码更安全,使用库(例如 Protocol Buffers)更智能。
关于c - 使用 __attribute__(__packed__) 填充结构,真的值得吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12304326/