How can I add a minimum compiler version requisite?

I want to create a project in C++11 and I use CMake as my build system.

How can I add a minimum compiler version requisite in the CMake config files?


AFAIK, there is no built-in support for something like this, but you could certainly write it yourself:

if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
  if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS "your.required.gcc.version")
    message(FATAL_ERROR "Insufficient gcc version")
  endif()
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
  if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS "your.required.msvc.version")
    message(FATAL_ERROR "Insufficient msvc version")
  endif()
elseif(...)
# etc.
endif()

However, I suggest you actually consider a feature-detection approach instead. That is, use try_compile() to verify that the compiler supports the features you need, and FATAL_ERROR if it doesn't. It's more idiomatic in CMake, and has the added benefit you don't have to discover the appropriate minimal version for all compilers out there.


Starting with CMake 2.8.10 the CMAKE_<LANG>_COMPILER_VERSION variables can be accessed by users to get the compiler version. In previous versions those were only reserved for internal purposes and should not be read by user code. They are also not guaranteed to be set for all languages but C and CXX should definitely be available.

CMake also contains operators for version comparison (VERSION_LESS, VERSION_EQUAL, VERSION_GREATER) that you can use to write your version validation code.

Remember that you will need to find out which compiler you have first and then check for the correct version.

Here is a short sample from one of my projects:

if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
    # require at least gcc 4.8
    if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.8)
        message(FATAL_ERROR "GCC version must be at least 4.8!")
    endif()
elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
    # require at least clang 3.2
    if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.2)
        message(FATAL_ERROR "Clang version must be at least 3.2!")
    endif()
else()
    message(WARNING "You are using an unsupported compiler! Compilation has only been tested with Clang and GCC.")
endif()

You can check the specific gcc version as follows:

if (CMAKE_COMPILER_IS_GNUCC AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.1)
    message(FATAL_ERROR "Require at least gcc-5.1")
endif()