gpt4 book ai didi

c - 在编译时查看结构体元素的大小?

转载 作者:行者123 更新时间:2023-11-30 21:00:24 26 4
gpt4 key购买 nike

如何在编译时查看结构体元素的大小?

我尝试过:

#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?”。 (这是另一篇文章所要求的),所以我不认为它是重复的。我问“如何在编译时查看结构元素的大小?这是一个不同的问题。

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

最佳答案

我很遗憾地说,以下丑陋、暴力的方法是我所能想到的。但它们有效。

方法一

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

#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 文件中的变量,它会告诉您它使用了多少字节。

关于c - 在编译时查看结构体元素的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41654561/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com