KabCode
KabCode

Reputation: 766

Cmake and Qt5: Using different components of Qt5 in different subdirectories

I want to use the Qt5 library in my subdirectories without adding the all components to each subdirectory. In the parent CMakeLists I use find_package(Qt5) to make sure that the library exists and the Qt5_DIR variable is set. Example:

CMakeLists.txt

cmake_minimum_required(VERSION 3.0)

find_package(Qt5 COMPONENTS Core REQUIRED)

add_subdirectory(exec1)
add_subdirectory(exec2) 

In the subdirectory exec1 I want to use the Qt5::Xml component. As far as I have understood CMake, the Qt5_DIR variable is passed to the subdirectories. Therefore I do not have to use find_package again. Is this assumption correct? Example:

exec1/CMakeLists.txt

project(exec1)
set(SRC exec1.cpp)
set(HDR exec1.h)

add_executable(exec1 ${SRC} ${HDR})
target_link_libraries(exec1 Qt5::Core Qt5::Xml)

In a second subdirectory exec2 I want to add other components of Qt5. Example:

exec2/CMakeLists.txt

project(exec2)
set(SRC exec2.cpp)
set(HDR exec2.h)

add_executable(exec2 ${SRC} ${HDR})
target_link_libraries(exec2 Qt5::Core Qt5::Websockets)

Does it make any difference if I add all components in the parent CMakeLists.txt instead of choosing for each subproject only some components? How do I handle this case so that I can exchange Qt5 components in the subdirectories without affecting other subdirectories? Or is it more convenient to add the find_package to each subdirectory instead of using it once in the parent CMakeLists.txt?

Any suggestions and tipps are appreciated.

Upvotes: 2

Views: 1302

Answers (1)

rocambille
rocambille

Reputation: 15956

If you want to use Qt5 components in subdirectories while using find_package only once in the root CMakeLists.txt -- which is IMHO the right thing to do -- you will have to list all the wanted components when finding Qt.

So following your example, root CMakeLists.txt should be something like that:

cmake_minimum_required(VERSION 3.0)

find_package(QT5 COMPONENTS Xml Websocket REQUIRED)

add_subdirectory(exec1) # will use Xml
add_subdirectory(exec2) # will use Websocket

Note that I removed Core since it is implicitly added as a dependency of both Xml and Websocket. Same goes for the subdirectories:

add_executable(exec1 ${SRC} ${HDR})
target_link_libraries(exec1 QT5::Xml)

Here exec1 implicitly links against Core component because it is a dependency of Xml.

Upvotes: 1

Related Questions