Clean way to detect if compiler supports enum deprecation

GCC versions 6 and later, as well as all most Clang versions, support deprecating enum values in C like this:

enum Foo {
    A = 1,
    B __attribute__ ((deprecated)) = A /* B is deprecated in favour of A */ 
};

However, several other compilers that claim compatibility with GCC 6 (by setting __GCC__ to a value greater than 6) do not support this. For example, neither the Intel compiler nor PGI do.

Is there a clean way to detect the availability of this feature with CMake? How should I go about it? I was looking at try_compile, but it seemed quite complicated, and couldn’t quite make it work.

You can use the CMake compiler detection for this. Something like:

set(enum_variant_deprecation_supported 0)
if (CMAKE_C_COMPILER_ID STREQUAL "GNU" # gcc
     OR …)
  set(enum_variant_deprecation_supported 1)
endif ()

# use the detection

Note that the consuming compiler also matters here, so some other detection may be required in that case. Here, you can use genexes to do this if condition to set the value to 1 or 0 that way.

See how VTK does this for Intel detection here.