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

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

    Though this isn't exactly at compile time, it is before runtime, so it could still be relevant for some people.

    You can define an array like so:

    uint8_t __some_distinct_name[sizeof(YourTypeHere)];
    

    And then, after compilation, get the size from the object file:

    $ nm -td -S your_object_file |       # list symbols and their sizes, in decimal
      grep ' __some_distinct_name$' |    # select the right one
      cut -d' ' -f2 |                    # grab the size field
      xargs printf "Your type is %d B\n" # print
    

提交回复
热议问题