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

后端 未结 12 1352
星月不相逢
星月不相逢 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:48

    You can't do this, not with structures. The preprocessor is invoked before compilation takes place, so there isn't even the concept of structure; you can't evaluate the size of something that doesn't exist / wasn't defined. The preprocessor does tokenize a translation unit, but it does so only for the purpose of locating macro invocation.

    The closest thing you can have is to rely on some implementation-defined macros that evaluate to the size of built-in types. In gcc, you can find those with:

    gcc -dM -E - 

    Which in my system printed:

    #define __SIZE_MAX__ 18446744073709551615UL
    #define __SIZEOF_INT__ 4
    #define __SIZEOF_POINTER__ 8
    #define __SIZEOF_LONG__ 8
    #define __SIZEOF_LONG_DOUBLE__ 16
    #define __SIZEOF_SIZE_T__ 8
    #define __SIZEOF_WINT_T__ 4
    #define __SIZE_TYPE__ long unsigned int
    #define __SIZEOF_PTRDIFF_T__ 8
    #define __SIZEOF_FLOAT__ 4
    #define __SIZEOF_SHORT__ 2
    #define __SIZEOF_INT128__ 16
    #define __SIZEOF_WCHAR_T__ 4
    #define __SIZEOF_DOUBLE__ 8
    #define __SIZEOF_LONG_LONG__ 8
    

    There is really nothing you can do to know the size of a custom struct without writing a program and executing it.

提交回复
热议问题