Search code examples
c++qtcmakesubdirectory

Qt library not available to subdirectory library when compiling with CMake but available to main directory executable


I have the following project structure:

CMakeLists.txt
main.cpp
Build/
OrderBook/
    CmakeLists.txt
    OrderBook.cpp
    OrderBook.hpp

The following is the contents of the TLD CMakeLists.txt:

cmake_minimum_required(VERSION 3.5)
project(OrderBookDemo)

set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(SQLite3 REQUIRED)
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets)

set(SOURCE_FILES main.cpp)
add_executable(OrderBookDemo ${SOURCE_FILES})

include_directories(OrderBook)

add_subdirectory(OrderBook)

target_link_libraries(OrderBookDemo OrderBook DBHandler Qt${QT_VERSION_MAJOR}::Widgets SQLite::SQLite3 )

The following is the contents of CMakeLists.txt in the OrderBook folder:

project (OrderBook)
add_definitions(-std=c++14)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

set(HEADER_FILES OrderBook.hpp)
set(SOURCE_FILES OrderBook.cpp)

add_library(OrderBook STATIC ${SOURCE_FILES} ${HEADER_FILES})

Interestingly, when I add #include <sqlite3.h to OrderBook.hpp, the project successfully compiles.

However, when I add #include <QApplication> to OrderBook.hpp, I get an error when compiling using cmake --build . The error is:

In file included from /Users/shreyashonnalli/desktop/Group Project/GroupRepo/DBHandler/DBHandler.cpp:8:
In file included from /Users/shreyashonnalli/desktop/Group Project/GroupRepo/DBHandler/DBHandler.hpp:14:
/Users/shreyashonnalli/desktop/Group Project/GroupRepo/OrderBook/OrderBook.hpp:11:10: fatal error: 'QApplication' file not found
#include <QApplication>
         ^~~~~~~~~~~~~~
1 error generated.

In addition, when I add #include <QApplication> and #include <sqlite3.h to main.cpp, it still compiles. This tells me the external libraries are made available to main.cpp in TLD, but ONLY sqlite3 is made available to the OrderBook/ files.

Why could this happen? How can I make Qt available to the subdirectories as well?

Please ignore the DBHandler parts of the code, as that it is irrelevant to the bare-bones representation of the problem.


Solution

  • An answer was found by appending target_link_libraries(<library_name> Qt${QT_VERSION_MAJOR}::Widgets) to the end of CMakeLists.txt within the OrderBook folder AND to all libraries which imported the OrderBook library.