我正在为一个非常简单的语言编写一个非常小的解释器,它允许简单的结构定义(由其他结构和简单类型组成,如int,char,float,double等).我希望字段尽可能少地使用字段,因此使用max_align_t或类似的东西是不可能的.现在,我想知道是否有更好的方法来获得除此之外的任何单一类型的对齐:
#include <stdio.h>
#include <stddef.h>
#define GA(type,name) struct GA_##name { char c; type d; }; \
const unsigned int alignment_for_##name = offsetof(struct GA_##name,d);
GA(int,int);
GA(short,short);
GA(char,char);
GA(float,float);
GA(double,double);
GA(char*,char_ptr);
GA(void*,void_ptr);
#define GP(type,name) printf("alignment of "#name" is: %dn",alignment_for_##name);
int main() {
GP(int,int);
GP(short,short);
GP(char,char);
GP(float,float);
GP(double,double);
GP(char*,char_ptr);
GP(void*,void_ptr);
}
这有效,但也许有更好的东西?
解决方法
这可能不是很便携,但GCC接受以下内容:
#define alignof(type) offsetof(struct { char c; type d; },d)
编辑:根据this answer,C允许转换为匿名结构类型(虽然我希望看到这个语句备份).所以以下应该是可移植的:
#define alignof(type) ((size_t)&((struct { char c; type d; } *)0)->d)
使用GNU statement expressions的另一种方法:
#define alignof(type) ({ \
struct s { char c; type d; }; \
offsetof(struct s,d); \
})