是否可以使用编译时计算将C/C++结构填充到固定大小?
是否可以在编译时计算结构中所需的填充数组的大小,以便该结构最终成为每个确定的大小。那就是我想做这样的事情(我知道这行不通)
#define APPDESCTARGETSIZE 256 // Target size for the App Desc Structure
// Structure member size of
#define msizeof(type, member) sizeof(((type *)0)->member)
// Size of padding arrary
#define padsize (APPDESCTARGETSIZE - (offsetof(custom_app_desc_t, pad) + msizeof(custom_app_desc_t, tail)))
/** * @brief Description about application. */
typedef struct {
uint8_t header[16];
char progname[16];
char boardname[16];
uint8_t chipsize;
uint8_t version_maj;
uint8_t version_min;
uint8_t version_iss;
uint8_t pad[padsize];
uint8_t tail[16];
} custom_app_desc_t;
我可以通过如下手动计算来解决,但编译器为我做数学运算会很好:
#define padsize (APPDESCTARGETSIZE - 68)
注意,在这种情况下,pad 出现在“tail”成员之前是很重要的。
回答
解决此问题的一种方法是使用union:
struct {
union {
struct {
// this is your structure, without the last element
};
char _reserved[APPDESCTARGETSIZE - 16]; // exclude the last tail element
};
char tail[16]; // the tail is outside of the padding
};
- You can leave the name off of the inner struct so that its members can be accessed directly.
- `_data` is not needed
- @TanveerBadar: So that it is after the padding, as requested in the question.