cmake Qt5 dll copy example


So let's say you have a project that depends on Qt5 and you need to copy the relevant dlls to your build directory and you don't want to do it manually; you can do the following:

cmake_minimum_required(VERSION 3.0)
project(MyQtProj LANGUAGES C CXX)
find_package(Qt5 COMPONENTS Core Gui Widgets)
#...set up your project

# add the executable
add_executable(MyQtProj ${PROJ_SOURCES} ${PROJ_HEADERS})
add_custom_command(TARGET MyQtProj POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_FILE:Qt5::Core> $<TARGET_FILE_DIR:MyQtProj>
    COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_FILE:Qt5::Gui> $<TARGET_FILE_DIR:MyQtProj>
    COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_FILE:Qt5::Widgets> $<TARGET_FILE_DIR:MyQtProj>

So now everytime you build your project, if the target dlls have changed that you want to copy, then they will be copied after your target (in this case the main executable) is built (notice the copy_if_different command); otherwise, they will not be copied.

Additionally, note the use of generator expressions here. The advantage with using these is that you don't have to explicitly say where to copy dlls or which variants to use. To be able to use these though, the project you're using (Qt5 in this case) must have imported targets.

If you're building in debug, then CMake knows (based on the imported target) to copy the Qt5Cored.dll, Qt5Guid.dll, and Qt5Widgetsd.dll to the Debug folder of you build folder. If you're building in release, then the release versions of the .dlls will be copied to the release folder.