How can I print the result of sizeof() at compile time in C?

后端 未结 12 1338
星月不相逢
星月不相逢 2020-11-29 20:47

How can I print the result of sizeof() at compile time in C?

For now I am using a static assert (home brewed based on other web resources) to compare the sizeof() re

12条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 21:47

    One more way (that actually works):

    char __foo[sizeof(MyStruct) + 1] = {[sizeof(MyStruct)] = ""};
    

    Works with old'ish gcc 5.x. Yields an error like this:

    a.c:8:54: error: initializer element is not computable at load time
    a.c:8:54: note: (near initialization for 'a[8]')
    

    p.s. obviously, this one is (very) gcc specific. All other methods weren't working for me.

提交回复
热议问题