Search code examples
cmakeqt-creator

How to add new C++ header and source files in Qt Creator with CMake build?


I am currently looking for a way to add new C++ header and source file from the Qt creator GUI Application with CMake builder.

The issue is CMakeLists.txt file is not including those files.

This is the CMakeLists.txt file

cmake_minimum_required(VERSION 3.5)

project(MyTest LANGUAGES CXX)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

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

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(Qt5 COMPONENTS Widgets REQUIRED)

if(ANDROID)
  add_library(MyTest SHARED
    main.cpp
    mainwindow.cpp
    mainwindow.h
    mainwindow.ui
  )
else()
  add_executable(MyTest
    main.cpp
    mainwindow.cpp
    mainwindow.h
    mainwindow.ui
  )
endif()

target_link_libraries(MyTest PRIVATE Qt5::Widgets)

I will then go to Qt Creator and create a new C++ file. (This file will create separate header(.h) and source(.cpp) files. If the file name is MyCustom, then it will create mycustom.h & mycustom.cpp files.

Those files are not automatically added into the add_executable() section of CMakeLists. I have to manually add them to add_executable() to include them. Is that the way Qt creator and CMakeLists work or is there another way?


Solution

  • Yes , As of version Qt Creator 4.10.2 . When you add new files it were not added to CMakeLists.txt by default. But you can make work around by using CMake file command.

    1. Move your source and header files to a new subfolder ( sources )
    2. Edit your CMakeLists.txt to include that.

    example:

    file(GLOB SRCS "${CMAKE_SOURCE_DIR}/sources/*.cpp")
    add_executable(MyTest ${SRCS})