Search code examples
qtcmakestatic-linking

How to add new source files from a subdirectory using CMake


I am using Qt in a way that the Qt-related files are in a separate subdirectory called "GUI", and I am using CMake, the relevant part of it is shown below:

include_directories(${Qt5Widgets_INCLUDES} GUI/include main/include)

add_definitions(${Qt5Widgets_DEFINITIONS})

file(GLOB_RECURSE QOBJECT_HEADERS
    "GUI/include/*.h"
)
file(GLOB_RECURSE QOBJECT_SOURCES
    "GUI/*.cpp"
)

QT5_WRAP_CPP(hdr_moc ${QOBJECT_HEADERS})

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${Qt5Widgets_EXECUTABLE_COMPILE_FLAGS}  -std=c++11 -Wall")

add_executable(simGUI main/sim_GUI.cpp ${QOBJECT_SOURCES}
    ${hdr_moc})
# Use the Widgets module from Qt 5.
target_link_libraries(simGUI Qt5::Widgets)

Basically this setup works, but when I add a new file (something like an custom widget), the new file compiles OK, but in the linking phase the new object is not found.

I used to delete the build subdirectory, and after that everything works fine.

Am I doing something wrong with CMake? I guess the symptoms are caused by some caching problem.


Solution

  • From CMake's documentation:

    We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate.

    The typical approach is to list all files manually.