c++ __attribute__((packed))
时间: 2023-10-30 21:05:36 浏览: 124
c++ package
The "__attribute__((packed))" is a GCC (GNU Compiler Collection) compiler attribute that can be used to instruct the compiler to pack the struct or union members without any additional padding. This means that the compiler will not insert any unused bytes between the members of a structure or union, which can save memory but may also impact performance due to unaligned memory accesses.
For example, the following code shows a struct definition with "__attribute__((packed))":
```
struct my_struct {
char a;
int b;
short c;
} __attribute__((packed));
```
With this attribute, the struct members will be packed together tightly, without any padding bytes. Without this attribute, the compiler may insert padding bytes between the members for alignment purposes.
It's important to note that using "__attribute__((packed))" can have side effects and may not be suitable for all use cases. For example, it can lead to unaligned memory accesses, which may cause performance issues on some architectures. It's recommended to use this attribute only when necessary and to carefully test the code for any unintended consequences.
阅读全文