假设您只是希望它帮助您确定目标系统上各种类型的大小,而不必在目标系统上实际运行程序,但您不打算将其作为某种集成工具进入构建系统,我可能会为您提供 hack...
hack 确实需要运行编译器来编译程序,但您不必在任何地方运行编译后的输出。事实上,这个 hack 旨在通过生成编译器错误告诉您您想知道的内容。
这里的小宏会导致编译器吐出对应给定类型大小的错误信息。它还会吐出一条关于“搜索结束”的错误消息,以防你传递给它的类型大于它检查的类型。这只是提醒您向宏添加更多行以便处理您感兴趣的类型的“方便”。
一些主要限制是:
- 这太骇人听闻了
- 它以一种可怕的方式告诉你信息
- 它仅适用于可以表示为单个单词的类型(因此,
typedef 对long double 之类的内容是必需的,如示例中所示)。
但如果你曾经对某种类型的大小感到好奇,并且不想在目标上实际运行程序以获取printf() 的信息,这可能会有所帮助。
以下是宏以及一些使用它的示例:
#if !defined( PASTE)
#define PASTE2( x, y) x##y
#define PASTE( x, y) PASTE2( x, y)
#endif /* PASTE */
#define SAY_IF_SIZEOF( type, size) static char PASTE( PASTE( PASTE( sizeof_, type), _is_), size) [(sizeof(type) == (size)) ? -1 : 1]
#define SAY_SIZEOF_END(type) static char PASTE( end_search_for_sizeof_, type)[-1]
#define SAY_SIZEOF(type) \
SAY_IF_SIZEOF( type, 1); \
SAY_IF_SIZEOF( type, 2); \
SAY_IF_SIZEOF( type, 3); \
SAY_IF_SIZEOF( type, 4); \
SAY_IF_SIZEOF( type, 5); \
SAY_IF_SIZEOF( type, 6); \
SAY_IF_SIZEOF( type, 7); \
SAY_IF_SIZEOF( type, 8); \
SAY_IF_SIZEOF( type, 9); \
SAY_IF_SIZEOF( type, 10); \
SAY_IF_SIZEOF( type, 11); \
SAY_IF_SIZEOF( type, 12); \
SAY_IF_SIZEOF( type, 13); \
SAY_IF_SIZEOF( type, 14); \
SAY_IF_SIZEOF( type, 15); \
SAY_IF_SIZEOF( type, 16); \
SAY_SIZEOF_END(type)
//here's where you get to ask about the size of a type
SAY_SIZEOF(float);
typedef long double long_double;
SAY_SIZEOF(long_double);
struct foo {
char x;
short y;
int* p;
};
struct bar {
char x;
int* p;
short y;
};
typedef struct foo foo_t;
typedef struct bar bar_t;
SAY_SIZEOF(foo_t);
SAY_SIZEOF(bar_t);
int main(void)
{
return 0;
}
以下是使用 GCC/MinGW 4.5.1 编译该程序的内容:
C:\temp\test.c:34:1: error: size of array 'sizeof_float_is_4' is negative
C:\temp\test.c:34:1: error: size of array 'end_search_for_sizeof_float' is negative
C:\temp\test.c:38:1: error: size of array 'sizeof_long_double_is_12' is negative
C:\temp\test.c:38:1: error: size of array 'end_search_for_sizeof_long_double' is negative
C:\temp\test.c:56:1: error: size of array 'sizeof_foo_t_is_8' is negative
C:\temp\test.c:56:1: error: size of array 'end_search_for_sizeof_foo_t' is negative
C:\temp\test.c:57:1: error: size of array 'sizeof_bar_t_is_12' is negative
C:\temp\test.c:57:1: error: size of array 'end_search_for_sizeof_bar_t' is negative
所以,你可以很容易地看到:
-
float 是 4 个字节
-
long double 是 12 个字节
-
struct foo 是 8 个字节
-
struct bar 为 12 个字节(与 struct foo 不同,由于对齐/填充差异)
希望这会有所帮助。实际上,有时我会想要这个...通常,如果我对嵌入式目标上的结构的大小感到好奇,我会在调试器中四处寻找该信息,或者我必须在调试中破解@987654331 @某处。
我认为这实际上会更容易使用:
- 想知道有多大
- 将
SAY_SIZEOF()“调用”放到源文件中
- 按 Shift-Ctrl-B(或任何用于编译/构建的热键),获取信息,然后
- 删除
SAY_SIZEOF()“通话”