Using CMake to check for C++11 features

I recently changed to CMake for a project of mine, a C++ project which uses C++11.

To see some examples:

To make sure that the features I want exists, I uses tests like these:

CHECK_CXX_SOURCE_COMPILES("int main() { void* p = nullptr; }"
    HAVE_NULLPTR
    FAIL_REGEX "use of undeclared identifier 'nullptr'")
if(NOT HAVE_NULLPTR)
    message(FATAL_ERROR "no `nullptr`")
endif()

CHECK_CXX_SOURCE_COMPILES("int main() { char c1[] = u8\"a\"; char16_t c2[] = u\"a\"; char32_t c3[] = U\"a\"; }"
    HAVE_UNICODE_LITERALS
    # clang++
    FAIL_REGEX "use of undeclared identifier 'u8'"
    FAIL_REGEX "use of undeclared identifier 'u'"
    FAIL_REGEX "use of undeclared identifier 'U'"
    FAIL_REGEX "unknown type name 'char16_t'"
    FAIL_REGEX "unknown type name 'char32_t'"
    # g++
    FAIL_REGEX "‘u8’ was not declared in this scope"
    FAIL_REGEX "‘char16_t’ was not declared in this scope"
    FAIL_REGEX "‘char32_t’ was not declared in this scope")

CHECK_CXX_SOURCE_COMPILES("int main() { char s[] = R\"delim(string)delim\"; }"
    HAVE_RAW_STRING_LITERALS
    # clang++
    FAIL_REGEX "use of undeclared identifier 'R'"
    # g++
    FAIL_REGEX "‘R’ was not declared in this scope")

The CMakeLists.txt file requires that nullptr is supported, but the UNICODE literals and raw string literals are yet optional only.

Leave a Reply