Nicolas Holthaus Nicolas Holthaus - 21 days ago 5
C++ Question

Test for supported Qt version with CMake

I'm using cmake to build a Qt project, and it uses some of the newer Qt features and requires at least version 5.3 to build properly. I'd like to be nice to the people trying to build the project and fail at cmake configure time with a logical error telling them their cmake version isn't recent enough, rather than with some esoteric build error.

I know that I'll be getting at least version 5.0 by simply using the module

find_package
syntax (i.e.
find_package(Qt5Widgets REQURIED)
), but it's not so obvious how to make sure I'm using the right minor version.
What's the easiest way to do this?

Answer

There's no direct way to do this with the Qt-provided cmake packages, but it's easy enough to query the Qt version using qmake. Assuming you have something similar to the following already in the cmake files to locate the Qt install

set(QTDIR $ENV{QTDIR} CACHE STRING "Qt install path")
list(APPEND CMAKE_PREFIX_PATH ${QTDIR})

you can check the version and fail the configure step if it's too low like so

set(QT_MINIMUM_VERSION 5.3.0)

# Test for supported Qt version
find_program(QMAKE_EXECUTABLE NAMES qmake HINTS ${QTDIR} ENV QTDIR PATH_SUFFIXES bin)
execute_process(COMMAND ${QMAKE_EXECUTABLE} -query QT_VERSION OUTPUT_VARIABLE QT_VERSION)
if(QT_VERSION LESS QT_MINIMUM_VERSION)
    MESSAGE(FATAL_ERROR "Minimum supported Qt version: ${QT_MINIMUM_VERSION}. 
    Installed version: ${QT_VERSION}")
endif()
Comments