在编译时查看struct元素的大小?

时间:2017-01-14 20:18:22

标签: c struct sizeof

如何在编译时查看struct元素的大小?

我试过了:

#define XSTR(x) STR(x)
#define STR(x) #x
#pragma message "Size of struct: " XSTR(sizeof(my_struct.element))

但它只是显示:

note: #pragma message: Size of struct: sizeof(my_struct.element)

我不想确定它的大小合适。我想知道它的大小。

编辑:我没有问“我如何使用sizeof?”。 (这是其他帖子的问题),所以我不认为它是重复的。我问“如何在编译时查看struct元素的大小?这是一个不同的问题。

我正在尝试解释为什么编译器将32位分配给16位结构。

1 个答案:

答案 0 :(得分:1)

我遗憾地说,以下丑陋,蛮力的方法是我能想到的。但他们的工作。

方法1

编译在与大小相对应的行处失败。通过检查哪一行失败,我知道struct元素的大小

#define STATIC_ASSERT_SIZE(an_item, a_siz) do { enum { dummy_var = 1/((an_item == a_siz)? 0 : 1 )}; } while (0)

STATIC_ASSERT_SIZE(sizeof(my_struct.element), 0);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 1);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 2);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 3);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 4);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 5);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 6);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 7);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 8);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 9);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 10);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 11);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 12);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 13);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 14);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 15);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 16);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 17);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 18);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 19);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 20);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 21);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 22);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 23);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 24);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 25);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 26);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 27);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 28);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 29);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 31);
STATIC_ASSERT_SIZE(sizeof(my_struct.element), 32);

方法2

假设它编译,请查看编译器生成的MAP文件中的变量,它告诉您它使用了多少字节。