What is the easiest way to find the sizeof a type without compiling and executing code?

前端 未结 4 1935
逝去的感伤
逝去的感伤 2021-01-20 08:04

I wrote a bash script to determine the size of gcc\'s datatypes (e.g. ./sizeof int double outputs the respective sizes of int and

4条回答
  •  无人及你
    2021-01-20 08:48

    You can use the 'negative array size' trick that autoconf (see: AC_COMPUTE_INT) uses. That way, you don't need to link or execute code. Therefore, it also works when cross compiling. e.g.,

    int n[1 - 2 * !(sizeof(double) == 8)];
    

    fails to compile if: sizeof(double) != 8

    The downside is, you might have to pass -DCHECK_SIZE=8 or something similar in the command line, since it might take more than one pass to detect an unusual value. So, I'm not sure if this will be any faster in general - but you might be able to take advantage of it.

    Edit: If you are using gcc exclusively, I think @wintermute's comment is probably the best solution.

提交回复
热议问题