For various reasons, I have some structs I want to force to be specific sizes (in this case 64 bytes and 512 bytes). Both however, are below the somewhat below the sizes I want them to be.
Is there anyway for me to tell the compiler to set them to these specific sizes and pad with zeros, or would I be best off just declaring an array inside the struct that makes up the excess space so that it aligns on the size I want?
You can use a union.
struct mystruct_s {
... /* who knows how long */
};
typedef union {
struct mystruct_s s;
unsigned char padding[512];
} mystruct;
This will ensure the union is 512 bytes or more. Then, you can ensure that it is no more than 512 bytes using a static assertion somewhere in your code:
/* Causes a compiler error if sizeof(mystruct) != 512 */
char array[sizeof(mystruct) != 512 ? -1 : 1];
If you are using C11, there is a better way to do this. I don't know anybody who uses C11 yet. The standard was published a matter of weeks ago.
_Static_assert(sizeof(mystruct) == 512, "mystruct must be 512 bytes");
Note that the only way to pad with zeroes is to put the zeroes there manually (calloc
or memset
). The compiler ignores padding bytes.
I don't think that there's any way to automatize this, at least in gcc which is the compiler I use. You have to pad your structs.
Be careful about automatic alignment of variables in your struct. For example struct example{ char a; int b; }
does not take 5 bytes, but 8.
来源:https://stackoverflow.com/questions/8705665/force-specific-struct-size-in-c