我这段 C 代码可以在编译时候输出结构体的大小,你们还有什么好点子, show me the code!

205 天前
 Exxfire
#include <stdio.h>

struct X
{
    int a;
    char c[10];
    short d;
};
char checker(int a)
{
    (void)a;
    return '1';
}

#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)

#define TEST(x)                                                              \
    do                                                                       \
    {                                                                        \
        char checkSizeOfInt[sizeof(x)] = {checker(&checkSizeOfInt)};         \
        _Pragma(TOSTRING(message("Value: " #x)))                             \
    } while (0);

int main() {
    TEST(struct X);
    return 0;
}
2277 次点击
所在节点    C
8 条回复
pipapa
205 天前
哪些编译器可以
Exxfire
205 天前
@pipapa 我用的 gcc 编译,其它没试。gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.12)
henix
204 天前
在 gcc 14 上修改之后会输出这些:

···
test.c: In function 'main':
test.c:21:51: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
21 | char checkSizeOfInt[sizeof(x)] = {checker((int)&checkSizeOfInt)}; \
| ^
test.c:26:5: note: in expansion of macro 'TEST'
26 | TEST(struct X);
| ^~~~
test.c:22:9: note: '#pragma message: Value: struct X'
22 | _Pragma(TOSTRING(message("Value: " #x))) \
| ^~~~~~~
test.c:26:5: note: in expansion of macro 'TEST'
26 | TEST(struct X);
| ^~~~
···

没看到什么结构体大小啊
open9527
204 天前
有什么用吗
csfreshman
204 天前
没什么用,执行和 3 楼一样
Exxfire
204 天前
@henix
var_para_num_test.c: In function ‘main’:
var_para_num_test.c:21:51: warning: passing argument 1 of ‘checker’ makes integer from pointer without a cast [-Wint-conversion]
char checkSizeOfInt[sizeof(x)] = {checker(&checkSizeOfInt)}; \
^
var_para_num_test.c:26:5: note: in expansion of macro ‘TEST’
TEST(struct X);
^
var_para_num_test.c:9:6: note: expected ‘int’ but argument is of type ‘char (*)[16]’
char checker(int a)
^
var_para_num_test.c:26:17: note: #pragma message: Value: struct X
TEST(struct X);
^
var_para_num_test.c:21:36: note: in definition of macro ‘TEST’
char checkSizeOfInt[sizeof(x)] = {checker(&checkSizeOfInt)};
yolee599
203 天前
https://stackoverflow.com/a/53884709
但是有什么用呢?
Exxfire
203 天前
@yolee599 在编译阶段获取信息意味着不用等待程序编译完成,并执行,可以节省时间,提升效率。
当然,我只是觉得这么干很有意思。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1111103

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX