Search code examples
c++g++clang++

Retrieving from gcc/clang a value known at compilation time


Consider the following compilatiom time constant VALUE defined by

struct foo  {  uint32_t a;  };

static constexpr int VALUE = sizeof(foo);

Note that the way the value is computed is not important here.

I would like to retrieve the value itself (4 in the example) as a result of the compilation; in other words,I don't want to build a binary and launch it in order to get this value.

I know that option -E allows to stop after pre-processing but at this stage the value is not yet known. Maybe there exists some compiler option that would allow this but I don't know it.

The only way I can think of is to put a static_assert(VALUE==-1) that will cause an error and hope that the error message will hold the value; it seems that gcc can do this but not clang.

Is there a better way and not compiler-dependant to get the constant value as a result of the compilation itself ?


Solution

  • This:

    template<auto> class error;
    error<VALUE> print;
    

    This prints:

    • clang error: implicit instantiation of undefined template 'error<4>'
    • gcc error: aggregate 'error<4> print' has incomplete type and cannot be defined
    • icx error: implicit instantiation of undefined template 'error<4>'
    • msvc error C2079: 'print' uses undefined class 'error<4>'

    See for yourself on Compiler Explorer. On all of them, you could grep on error<[0-9]+> to retrieve the 4.