Search code examples
c++cmakemoduleqt5find-package

How to check an OPTIONAL_COMPONENT using find_package in cmake?


I want to build a specific feature of a GUI only if a certain component of a package is found. If not, the GUI should be built either way, but without this feature. The idea would be something like this, but I don't know the correct notation (or even if it is possible at all) to check the component itself:

find_package(Qt5 QUIET COMPONENTS Core Widgets OPTIONAL_COMPONENTS Charts)

if (Qt5_FOUND)
    message(STATUS "Gui enabled")
    ...
    if (Charts_FOUND) // This is the check I want to make
        message(STATUS "Optional feature enabled")
        ...
    else()
        message(STATUS "QtCharts not found")
    endif()
...

In cmake documentation: Finding Packages, in the Built-In Find Modules it says..

<XX>_<YY>_FOUND
If false, then the optional <YY> part of <XX> package is unavailable.

So I tried if(Qt5_Charts_FOUND) , but still, QtCharts is not found.

I am sure QtCharts is installed and working.


Solution

  • The way of determine whether a component is found depends on the package.

    "Built-In Find Modules" referred by the CMake tutorial are those Find modules which are shipped with CMake itself. They are documented here: https://cmake.org/cmake/help/latest/manual/cmake-modules.7.html#find-modules. As you could find, this list doesn't contain FindQt5 module.

    Since Qt5 defines IMPORTED target Qt5::<component> for every component which is found, one could assume that such target won't be defined for an optional component which is missed:

    find_package(Qt5 QUIET COMPONENTS Core Widgets OPTIONAL_COMPONENTS Charts)
    if (Qt5_FOUND)
        # Qt5 has been found, will all required components
        if(TARGET Qt5::Charts)
           # Charts component has been found
        else()
           # Charts component hasn't been found
        endif()
    endif()
    

    If a package is searched by a Find script, and that script uses find_package_handle_standard_args helper, then given helper processes "optionality" of components by treating the variable <PackageName>_<Component>_FOUND as indicator of whether component is found.

    If a package is searched by a Config script, then given script should process "optionality" of components by checking variables <PackageName>_FIND_REQUIRED_<Component>. E.g. the script QtConfig.cmake performs such checks. Not all Config scripts check that variables. A scripts which doesn't check that variables treats (incorrectly) optional components as required ones.