Tracked down difficult bug: caused by try_compile() using -D${_var}


In my primecount project I added the following test to check if __int128_t is supported by the C++ compiler and the C++ standard library:

    #include <limits>
    #include <type_traits>
    int main() {
        static_assert(std::numeric_limits<__uint128_t>::max() != 0, \"\");
        static_assert(std::is_integral<__int128_t>::value, \"\");
        static_assert(std::is_integral<__uint128_t>::value, \"\");
        static_assert(std::is_signed<__int128_t>::value, \"\");
        static_assert(std::is_unsigned<__uint128_t>::value, \"\");
        return 0;
    }" int128_t)

That test did not work reliably. Somehow I could fix the issues I encountered by changing the output variable name to int128 instead of int128_t. This is really scary to me, why does the test result depend on the output variable name?! So I read the CMake source code and found that check_cxx_source_compiles() uses try_compile() internally and there I found (CMake/CheckSourceCompiles.cmake at 1d225c5c0ca86592e835b626c55aa6bf4faa2f3d · Kitware/CMake · GitHub):

function(CMAKE_CHECK_SOURCE_COMPILES _lang _source _var)

Why is -D${_var} needed? I think this causes the bug I encountered. It seems to me that the -D${_var} definition makes it impossible to e.g. use an output variable name in check_cxx_source_compiles() that corresponds to any C/C++ keyword! There are loads of C/C++ keywords and new one are introduced from time to time. Even worse than that if the output variable name is used e.g. as a variable or function name inside the C/C++ test code or any of its headers the test will also fail!

I have convinced myself that this is a CMake bug, therefore I have reposted this issue on the CMake Gitlab issue tracker: