- How to release a Qt/C++ application on Linux and Windows?
- 2 Answers 2
- Развертывание Qt и QML приложений в Linux и Windows
- Для начала немного теории.
- Зачем это нужно?
- Теперь небольшое описание.
- Возьмем пример.
- MyApp (main.cpp)
- MyApp (main.qml)
- Общее
- Getting Started
- Supported Platforms
- Building from Sources
- Supported Compilers
- Configuring Qt
- Configuring Qt for Windows
- Configuring Qt for Linux
- Configuring Qt for macOS
- Third Party Dependencies
- Installing Dependencies for Windows
- Installing Dependencies for Linux
- Installing Dependencies for macOS
- Troubleshooting
- Setting up Qt Installer Framework
How to release a Qt/C++ application on Linux and Windows?
I developped an application in C++ using Qt for the graphic interface and now I would like to release it for linux and for Windows. I’ve been looking through documentation, forums and tutorials but I can’t really understand what need to be done. I’m pretty confused between the different terms used : what is the difference between releasing and deploying ? when do you need an installer and if needed, how to create one ? What are the different steps to create the .exe of Windows ? and its equivalent for the different versions of Linux (Debian, Ubuntu, Ubuntu Mate)? I am currently on Ubuntu and used Qt Creator to code the application. As far as I know, I need to deploy Shared Libraries. Any help, answer, guide or documentation for beginner would be of great help and very welcome 🙂
What kind of application are you developing? In what context (a research prototype, a commercial product)? For what audience (fellow academics, or general consumer)? Proprietary binary, or open source? What code size? Please edit your question to improve it and give more details (including the distributions that matter to you)
2 Answers 2
There are several ways to deploy your application
1. Deploy your application with windeployqt/linuxdeployqt
This is the easiest way, windeployqt or linuxdeployqt is an application that will copy all required dependencies to your executable folder. Ready to run on another computer.
- Compile your binary in release mode
- Open the Qt developer console and type windeployqt «C:\folder\of\your\executable» (linuxdeployqt will be very similar)
- All libraries required to run the application on another computer are copied to to your application folder. You can create an archive and send it to someone else.
2. Static build
Static build will be a single binary at the end that includes all Qt code. You can ship your single binary to someone, no additional libraries are required to run it. The executable is larger since all the Qt code is linked inside your executable.
The steps are as following:
- Download the Qt source code
- Unzip it to a folder
- Open the developer console of your installed compiler (i. e. MingW or MSVC)
- Switch to the folder and type ./configure -static -static-runtime
- When the configuration is done type nmake or make to build Qt statically.
- When the build process has finished create a new kit in Qt Creator and select the new qmake.exe or qmake from your source-code folder.
- Select in the project settings your kit to build a statically executable that requires not additional libraries.
3. Offline/Online Installer
This step requires some reading and fine tuning. Qt comes with an IFW (Installer Framework) where you can create online and offline installers. The installer will contain a .7z file of your executable and all dependencies. The installer is more comfortable for the user. It can create shortcuts, check available disk space, etc.
IIRC you need build the installer statically for MSVC or you have to ship the runtime libraries. If build with MingW you probably will not need any runtime libraries.
It is up to you which method you choose. If you own the commerical license you can ship all your closed source as static builds, but in general it’s better to ship it as a dynamic build especially if you use OpenSSL where users can quickly exchange vulnerable libraries themself if required.
Развертывание Qt и QML приложений в Linux и Windows
В этой статье мы рассмотрим, как правильно собрать все зависимости qt для вашего приложения, которое было собрано динамически.
Для начала немного теории.
Зачем это нужно?
- Статическая сборка.
Статическая сборка предполагает создание бинарника, в котором будут все необходимые ссылки на него. Другими словами, в нем будет лежать все, что нужно для его работы. Этот подход подходит для небольших консольных приложений, у которых мало зависимостей, иначе размер конечного бинарного файла будет чрезвычайно большим. - Динамичная сборка.
Отличается от статического тем, что в бинарнике будет только исходный код вашего приложения (размер бинарника будет минимальным), но при запуске такого приложения ему потребуются сторонние библиотеки, которые использовались при его написании.
Теперь небольшое описание.
Console-QtDeployer — это простая утилита, похожая на windeployqt и macdeployqt . Но в отличии от аналогов у него гораздо более гибкий интерфейс (флаги запуска) и более высокая скорость, к тому же он поддерживает 2 платформы windows и linux, а значит теперь мы можем строить зависимости для windows на линуксе и наоборот.
Возьмем пример.
Например, я написал простое qt-приложение с использованием qml — MyApp.
MyApp (main.cpp)
#include #include int main (int argc, char * argv []) < QCoreApplication :: setAttribute (Qt :: AA_EnableHighDpiScaling); QGuiApplication app (argc, argv); QQmlApplicationEngine engine; engine.load (QUrl (QStringLiteral ("qrc: /main.qml"))); if (engine.rootObjects (). isEmpty ()) return -1; return app.exec (); >MyApp (main.qml)
import QtQuick 2.9 import QtQuick.Controls 2.2 ApplicationWindow < visible: true width: 640 height: 480 title: qsTr ("Scroll") ScrollView < anchors.fill: parent ListView < width: parent.width model: 20 delegate: ItemDelegate < text: "Item" + (index + 1) width: parent.width >> > >MyApp подключается динамически, то есть для работы ему нужны библиотеки qt.
Если мы попытаемся запустить приложение, то сразу после сборки получим ошибку:~/build-MyApp-Desktop_Qt_5_11_1_GCC_64bit4-Release $ ./MyApp ./MyApp: /usr/lib/x86_64-linux-gnu/libQt5Qml.so.5: version `Qt_5 'not found (required by ./MyApp) ./MyApp: /usr/lib/x86_64-linux-gnu/libQt5Gui.so.5: version `Qt_5 'not found (required by ./MyApp) ./MyApp: /usr/lib/x86_64-linux-gnu/libQt5Core.so.5: version `Qt_5.11 'not found (required by ./MyApp) ./MyApp: /usr/lib/x86_64-linux-gnu/libQt5Core.so.5: version `Qt_5 'not found (required by ./MyApp)Из подобных текстов мы видим, что приложение зависит от графических библиотек qt и qml. Поиск и сборка всех ресурсов (библиотек и плагинов) займет много времени.
Для экономии времени и сил воспользуемся утилитой CQtDeployer (ее можно скачать здесь )
или установить в Snap Storecqtdeployer -bin myApp -qmake /media/D/Qt/5.12.3/gcc_64/bin/qmake -qmlDir ./После выполнения этой команды вы получите полностью готовое приложение для работы с готовым лаунчером, который настроит все необходимые окружения для работы вашего приложения на всех машинах под управлением Linux.
Общее
После запуска Консоли QtDeployer содержимое папки с вашим приложением должно выглядеть так:
drwxr-xr-x 7 andrei andrei 4096 May 24 12:22 ./ drwxrwxr-x 3 andrei andrei 4096 May 24 12:22 ../ drwxr-xr-x 2 andrei andrei 4096 May 24 12:22 bin/ drwxr-xr-x 2 andrei andrei 4096 May 24 12:22 lib/ -rwx---rwx 1 andrei andrei 433 May 24 12:22 myApp.sh* drwxr-xr-x 6 andrei andrei 4096 May 24 12:22 plugins/ drwxr-xr-x 5 andrei andrei 4096 May 24 12:22 qml/ drwxr-xr-x 2 andrei andrei 4096 May 24 12:22 translations/
- myApp.sh - скрипт запуска вашего приложения
- bin - папка с вашим бинарником
- lib - папка со всеми необходимыми зависимостями вашего приложения.
- plugins - qt плагины, необходимые для работы приложения
- qml - qml зависимости.
- translations - стандартные переводы qt.
Таким образом, вы можете подготовить свое приложение к упаковке в deb или snap пакет, после чего можете приступить к его распространению. Обратите внимание, что после запуска cqtdeployer ваше приложение должно быть запущено с помощью скрипта sh, который настроит необходимое окружение для вашего приложения.
Рекомендуем хостинг TIMEWEB
Стабильный хостинг, на котором располагается социальная сеть EVILEG. Для проектов на Django рекомендуем VDS хостинг.
Рекомендуемые статьи по этой тематике
По статье задано0 вопрос(ов)
Вам это нравится? Поделитесь в социальных сетях!
Getting Started
You can use the Qt Installer Framework to create installation programs for all kinds of applications, including (but not limited to) applications built with Qt.
Supported Platforms
You can use the Qt Installer Framework to create installers for all platforms supported by desktop Qt.
Building from Sources
The following steps describe how to build the Qt Installer Framework yourself. You can skip this if you have downloaded a pre-built version of the framework.
Supported Compilers
You can compile the Qt Installer Framework with Microsoft Visual Studio 2015 and newer, GCC 5 and newer, and Clang 11.0.0 and newer. Currently, the tested combination for Windows is Qt 5.15.2 with MSVC 2015 (Windows 10).
Configuring Qt
If you use a statically built Qt to build the Qt Installer Framework you do not have to deliver Qt libraries, which enables you to distribute installers as one file. For more information about statically linking against OpenSSL libraries, see SSL Import and Export Restrictions. The supported Qt version is 5.15.2.
Configuring Qt for Windows
configure -prefix %CD%\qtbase -release -static -static-runtime -accessibility -no-icu -no-sql-sqlite -no-qml-debug -nomake examples -nomake tests
nmake (or 'mingw32-make') module-qtbase module-qtdeclarative module-qttools module-qttranslations module-qtwinextras
Configuring Qt for Linux
configure -prefix $PWD/qtbase -release -static -accessibility -qt-zlib -qt-libpng -qt-libjpeg -qt-pcre -no-glib -no-cups -no-sql-sqlite -no-feature-gssapi -no-qml-debug -no-opengl -no-egl -no-xinput2 -no-sm -no-icu -nomake examples -nomake tests -no-libudev
make module-qtbase module-qtdeclarative module-qttools module-qttranslations
Configuring Qt for macOS
configure -prefix $PWD/qtbase -release -static -no-securetransport -accessibility -qt-zlib -qt-libpng -qt-libjpeg -no-cups -no-sql-sqlite -no-qml-debug -nomake examples -nomake tests -no-freetype
make module-qtbase module-qtdeclarative module-qttools module-qttranslations
Third Party Dependencies
The Qt Installer Framework sources contain a redistribution of parts of the libarchive compression and archive library, which requires you to link against the following libraries; liblzma , zlib , libbzip2 , and on macOS, libiconv . To enable the use of libarchive , add the libarchive configuration feature to the list of values specified by the CONFIG variable. Installers created with this configuration support the creating and extracting of 7zip, zip, and tar archive files, with gzip , bzip2, and xz as available compression methods.
You can use the IFW_ZLIB_LIBRARY , IFW_BZIP2_LIBRARY , IFW_LZMA_LIBRARY , and IFW_ICONV_LIBRARY variables to specify the exact library files. If you add the -qt-zlib configuration to the Qt version used to build the Qt Installer Framework, and IFW_ZLIB_LIBRARY variable is empty, libarchive will try to use the zlib library compiled into the QtCore module, which removes the need for an external library. If you do not enable libarchive support, the builtin LZMA SDK library will act as a fallback and installation of the extra dependencies will not occur, but created installers will only support the 7zip format.
Installing Dependencies for Windows
When building the third party libraries with MSVC, make sure to use the same version that you used to build Qt, and that the compiler option used to select the run-time library matches the configuration options for Qt (debug/release, static/dynamic runtime).
Installing Dependencies for Linux
The required third party compression libraries are likely available from your distribution's package manager repositories.
For example, on Ubuntu 18.04 you can invoke the following to install the development packages containing headers for the libraries:
sudo apt install zlib1g-dev liblzma-dev libbz2-dev
Installing Dependencies for macOS
The easiest way to install the missing libraries is with a third party package manager solution, like Homebrew or MacPorts. On macOS 10.15 you should only need to additionally install the liblzma library.
On Homebrew this would be:
Troubleshooting
For libarchive related compilation errors, you may need to edit the definitions in a configuration header file respective to your platform. You can find this file in the src/libs/3rdparty/libarchive/config/ directory of the Installer Framework sources.
Setting up Qt Installer Framework
- Clone the Qt Installer Framework source code from http://code.qt.io/cgit/installer-framework/installer-framework.git/ to get the sources for the tools.
- Build the tools by running the "qmake" from the static Qt, followed by "make" or "nmake".
Note: To contribute patches to Qt Installer Framework, follow the standard Qt processes and guidelines. For more information, see Contribute to Qt.
© 2021 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. The Qt Company, Qt and their respective logos are trademarks of The Qt Company Ltd in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.