Building C++ Applications with Qt SDK's CMake Modules

I personally find the Qt SDK to be feature-rich and seemingly all-encompassing, however the mode selector in Qt Creator can be restricting and jarring, especially for those like me who are familiar with being able to perform all tasks, and manage my project all from the comfort of a single workspace, such as in Microsoft's Visual Studio. This post isn't about choosing another IDE, instead it's about you can build Qt applications easily outside of Creator using Qt's supplied CMake modules.

For the latter reason, and because the CMake syntax has highlighting and automatic completion support in many IDE's (including my favourite on Ubuntu, KDevelop), I created an experimental project containing a 'CMakeLists.txt' which would utilize the CMake modules provided by Qt. With a few tweaks, namely to path variables and compiler flags, it's possible to generate a Makefile that will link with Qt's libraries.

Here is the source code for that CMake script from my project. This 'CMakeLists.txt' file only differs slightly from one generated by the CMake project wizard in Creator, in that 'CMAKE_PREFIX_PATH' isn't already configured so it is set manually:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
cmake_minimum_required(VERSION 2.8.12)
project(hello_qt)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_PREFIX_PATH "/home/ben/Qt/5.10.1/gcc_64/lib/cmake")
set (CMAKE_CXX_STANDARD 11)
find_package(Qt5Core CONFIG REQUIRED)
find_package(Qt5Widgets CONFIG REQUIRED)
set(SOURCES
    "src/main.cpp"
)
add_executable(hello_qt ${SOURCES})
target_compile_options(hello_qt PRIVATE -fPIC)
target_link_libraries(hello_qt Qt5::Widgets)

I've tested it, and can confirm that it works. For the sake of brevity, you could generate the Makefile and process it with 'cmake --clean-first --build .'.

NB: The PIC compiler flag is important, as it's for generating 'position independant code' which means that the machine code is not dependant on being in a certain location to work, and so that the linked libraries are relocatable in memory at runtime.

Comments

Saturnina Sprunger 10 months, 1 week ago

Good to see your post.

Link | Reply
Currently unrated

New Comment

required

required (not published)

optional

required