Ç - 获取型排列可移植 [英] C - get type alignment portably
问题描述
我正在写非常小的跨preTER一个非常简单的语言,它允许简单的结构定义(由其他结构和简单的类型,如int,char和float,double和这样的一个)。我想域使用尽可能少排列的可能,因此,使用max_align_t或类似的东西是毫无疑问的。现在,我不知道是否有一个更好的方式来获得任何单一类型的其他比这对准:
I'm writing really small interpreter for a very simple language, which allows for simple structure definitions (made of other structures and simple types, like int, char, float, double and so one). I want fields to use as little alignment as possible, so using max_align_t or something similar is out of question. Now, I wonder if there is a nicer way to get alignment of any single type other than this:
#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);
}
这工作,但也许有更好的东西?
This works, but maybe there is something nicer?
推荐答案
<打击>这可能不是非常便携,但击>海湾合作委员会接受如下:
This is probably not very portable, but GCC accepts the following:
#define alignof(type) offsetof(struct { char c; type d; }, d)
编辑:并按照这个答案,C允许铸造匿名结构类型(虽然我想看到这个说法备份)。所以下面应该是可移植:
And according to this answer, C allows casting to anonymous struct types (although I'd like to see this statement backed up). So the following should be portable:
#define alignof(type) ((size_t)&((struct { char c; type d; } *)0)->d)
#define alignof(type) ({ \
struct s { char c; type d; }; \
offsetof(struct s, d); \
})
这篇关于Ç - 获取型排列可移植的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!