- Статическая линковка библиотек Qt 5.x (MinGW) под Windows
- Подготовка
- Начнем
- Статическая линковка Qt 5.x.x с MinGW32 в Windows (сборка в один exe’шник)
- Windows qt static build windows
- Qt Documentation
- Contents
- The Windows Deployment Tool
- Static Linking
- Linking the Application to the Static Version of Qt
- Shared Libraries
- Building Qt as a Shared Library
- Linking the Application to Qt as a Shared Library
- Creating the Application Package
- Manifest files
- Application Dependencies
- Additional Libraries
- Ensuring Plugins Are Found when Using Non-Relocatable Builds
Статическая линковка библиотек Qt 5.x (MinGW) под Windows
В данной статье я опишу как сделать отдельный комплект со статической линковкой библиотек Qt5. Если другими словами, мы сможем собирать проект в один исполняемый файл без Qt *.dll.
Подготовка
Начнем
Сборка комплекта
- Создаем резервную копию qmake.conf, он находится в «Qt5.5.0\5.5\mingw492_32\mkspecs\win32-g++»
- Делаем изменения в qmake.conf
- Создаем резервную копию исходников Qt, они находятся в «Qt5.5.0\5.5\Src»
- Теперь запускаем терминал Qt — Qt 5.5 for Desktop (MinGW 4.9.2 32 bit), он находится
в «Все программы -> Qt5.5.0 -> 5.5 -> MinGW 4.9.2 (32-bit)» или же полным путем «%appdata%\Microsoft\Windows\Start Menu\Programs\Qt 5.5.0\5.5\MinGW 4.9.2 (32-bit)« - Переходим в директорию с исходниками Qt, вводим команду
- Конфигурируем этап установки, вводя команду, где путь после -prefix, местоположение комплекта сборки
- По завершению конфигурирования, начинаем компиляцию исходников Qt, командой
После компиляции, будет несколько ошибок, не обращаем на них внимание, они никак не скажутся на нашей сборке.
Копируем файлы в указанный нами каталог на этапе конфигурирования, командой
После копирования, так же будет несколько ошибок, не обращаем на них внимание.
Добавляем статичный комплект в Qt Creator
- Запускаем Qt Creator
- Открываем «Инструменты -> Параметры..»
- Далее переходим «Сборка и запуск -> Qt Versions»
- Жмем добавить и выбираем qmake.exe, точнее «X:\Qt\Qt5.5.0_Static\bin\qmake.exe»
- Переходим во вкладку «Комплекты»
- Жмем добавить
- Пишем название нашего комплекта «Qt 5.5.0 Static MinGW 32», в профиле Qt указываем наш статичный профиль, который добавили в Qt Versions, так же указываем версию нашего компилятора и отладчика(MinGW)
- Все, мы добавили статичный комплект в Qt Creator
Примечание: в статический комплект не будут включены библиотеки gcc, что бы они так же собирались в исполняемый файл, надо прописать в .pro/.pri
Спасибо за внимание!
Данная статья не подлежит комментированию, поскольку её автор ещё не является полноправным участником сообщества. Вы сможете связаться с автором только после того, как он получит приглашение от кого-либо из участников сообщества. До этого момента его username будет скрыт псевдонимом.
Статическая линковка Qt 5.x.x с MinGW32 в Windows (сборка в один exe’шник)
Доброго времени суток, хабравчане!
Я уверен, что все заметили, когда делали деплой своей программы через windeployqt.exe, программа зависит от разных динамических и qt’шных библиотек. Вследствие чего, развертка на других компьютерах становится неудобной. Почему? Приходится держать сам exe’шник в папке с нужными библиотеками. Разумеется, можно умудриться и без статической линковки решить эту проблему. Согласитесь, неудобно, да и каждый раз нужно лишние телодвижения делать. Проще один раз запариться и потом не делать лишних движений. Еще один плюс статической линковки — размер файла. При динамической линковке сам exe’шник весит примерно от 1 МБ до 7-8 МБ, а с окружением до 70 МБ может спокойно дойти, даже если проект небольшой. При статической линковке есть только exe’шник, который весит примерно в 2 раза меньше, чем окружение при динамической линковке.
Для сборки необходимы:
- Qt 5.x.x с включенными компонентами (если Qt уже был установлен, нужные компоненты можно установить с помощью Qt Maintenance Tool):
- Qt — Qt 5.x — MinGW x.x.x 32 bit
- Qt — Qt 5.x — Sources
- Qt — Tools — MinGW
- Perl (Strawberry Perl, к примеру). Я использую strawberry-perl-5.30.2.1-32bit.
Проверить, что путь к исполняемому файлу Perl прописан в переменной окружения PATH. Этот пункт можно пропустить, но лучше проверить. - Python 3.8
Путь установки Qt неважен, у меня он установлен на диске D. Убедитесь, что объем доступной памяти вам хватит. Нужно как минимум 30 ГБ свободного места.
- Переходите в директорию, где папка Src (D:\Qt\5.x.x\Src);
- Там создайте папку static (D:\Qt\5.х.х\static);
- Папку Src копируйте в папку static. Получится D:\Qt\5.x.x\static\Src. Дальнейшие действия будут там, в Папке Src;
- Создайте папку mingwXX_32 (у меня, например, mingw73_32). Получится D:\Qt\5.x.x\static\mingwXX_32;
- Редактируйте файл qmake.conf, который находится в D:\Qt\5.х.х\static\Src\qtbase\mkspecs\win32-g++.
В самый конец файла, после строки load(qt_config) допишите с новой строки эти команды:
Командная строка MinGW будет выдана как Qt 5.x.x (MinGW x.x.x 32-bit)
set LANG=en
cd /d %QT_INSTALL_PREFIX%\..\Src (именно такая строка без изменений)
Тут стоит обратить внимание на опцию -no-ssl — это значит что Qt будет собран без поддержки SSL.
Если никаких ошибок нету, можно продолжать:
Нереально длительный процесс, можете смело забыть про него на 4 часа ориентировачно, от скорости чтения/записи диска не зависит, а зависит от процессора. Там где -j4 вместо 4 поставьте число ядер вашего процессора.
В результате получаем статическое окружение в D:\Qt\5.x.x\statiс\mingwXX_32;
- В верхнем меню Инструменты -> Параметры -> Профили Qt
- Добавить -> D:\Qt\5.х.х\static\mingw73_32\bin\qmake.exe -> Применить
- Комплекты -> Добавить
- Название: Qt static x32 (или какое угодно)
- Тип Устройства: Desktop
- Устройство: Локальный ПК
- Корень образа: D:\Qt\5.х.х\static
- Компилятор:
a) для С: MinGW x.x.x 32-bit for C
b) для С++: MinGW x.x.x 32-bit for C++ - Профиль Qt: Qt static x32 (название профиля, которое вы указали при добавлении профиля)
- Применить -> Ок
Дополнительная информация. У меня:
- Qt 5.14.1
- MinGW 7.3.0 32-bit (mingw73_32)
- Python 3.8 x32
- strawberry-perl-5.30.2.1-32bi
- Windows 10 Pro x64
Полет нормальный.
Брал информацию отсюда:
Данная статья не подлежит комментированию, поскольку её автор ещё не является полноправным участником сообщества. Вы сможете связаться с автором только после того, как он получит приглашение от кого-либо из участников сообщества. До этого момента его username будет скрыт псевдонимом.
Windows qt static build windows
Статическая сборка проекта Qt под Windows.
Отвязка проекта, сделанного в Qt, от .dll зависимости.
При создании проекта релиза, программа не будет запускаться на другом компьютере без дополнительных библиотек. Это не очень удобно, потому как при потере даже одной, ваш знакомый не увидит ваше творчество. К тому же, они придают программе дополнительный размер. И это тоже минус.
Смотрим данное видео.
Пошаговая настройка статической сборки Qt для Windows:
1. Скачиваем Qt c http://www.qt.io/download-open-source/#section-2 (Открывается в новом окне)
2. Устанавливаем Qt. При установке нажимаем кнопку «Выбрать все»
3. Переходим в папку C:\Qt\ Qt5.5.0 \ 5.5 \Src\qtbase\mkspecs\win32-g++\ ( Подчеркнутое — Изменить под свою версию)
4. Редактируем qmake.conf
5. Переходим в папку Qt\ Qt5.5.0 \ 5.5 \Src\qtbase\ ( Подчеркнутое — Изменить под свою версию)
6. Прямо в папке qtbase создаем батник Install.bat с кодом, который написан внизу или копируем уже готовый.
Код батника (Install.bat):
Внимание! на строчку
set PATH=c:\Qt\Qt5.5.0\5.5\mingw492_32\bin;c:\Qt\Qt5.5.0\Tools\mingw492_32\bin;%PATH% Измените Qt5.5.0\5.5 на свою версию.
8. Запускаем батник, соглашаемся с лицензией, нажимаем «y» и ожидаем окончании работы.
По окончании выполнения батника, делаем следующее:
9. Запускаем Qt Creator.
10. Переходим «Инструменты» -> «Параметры» -> «Сборка и запуск» -> «Qt Versions» и нажимаем «Добавить»
11. Добавляем путь C:\Qt\ Qt5.5.0\5.5 \Src\qtbase\bin\qmake.exe ( Подчеркнутое — Изменить под свою версию)
12. Для большей удобности в «Название профиля» дописываем Static. Жмем кнопку «Применить».
13. Переходим в «Комплекты» и нажимаем «Добавить»
14. Меняем «Название» на Static.
15. В «Профиль Qt:» меняем на новый профиль «Qt 5.5.0 (Src) Static». Жмем кнопку «ОК» или «Применить».
Все готово. Теперь проверяем на простой программе и приступаем к программированию.
Qt Documentation
Contents
This documentation describes deployment process for Windows. We refer to the Plug & Paint example application through out the document to demonstrate the deployment process.
The Windows Deployment Tool
The Windows deployment tool windeployqt is designed to automate the process of creating a deployable folder containing the Qt-related dependencies (libraries, QML imports, plugins, and translations) required to run the application from that folder. It creates a sandbox for Universal Windows Platform (UWP) or an installation tree for Windows desktop applications, which can be easily bundled into an installation package.
The tool can be found in QTDIR/bin/windeployqt . It needs to be run within the build environment in order to function correctly. When using Qt Installer, the script QTDIR/bin/qtenv2.bat should be used to set it up.
windeployqt takes an .exe file or a directory that contains an .exe file as an argument, and scans the executable for dependencies. If a directory is passed with the —qmldir argument, windeployqt uses the qmlimportscanner tool to scan QML files inside the directory for QML import dependencies. Identified dependencies are then copied to the executable’s directory.
In case Qt was built with the configure switch -relocatable turned off, windeployqt replaces the hardcoded local paths in Qt5Core.dll by relative ones.
For Windows desktop applications, the required runtime files for the compiler are also copied to the deployable folder by default (unless the option —no-compiler-runtime is specified). In the case of release builds using Microsoft Visual C++, these consist of the Visual C++ Redistributable Packages, which are intended for recursive installation by the application’s installer on the target machine. Otherwise, the shared libraries of the compiler runtime are used.
The application may require additional 3rd-party libraries (for example, database libraries), which are not taken into account by windeployqt.
Additional arguments are described in the tools’ help output:
Static Linking
To build static applications, build Qt statically by configuring Qt with -static :
If you later need to reconfigure and rebuild Qt from the same location, ensure that all traces of the previous configuration are removed by entering the build directory and running nmake distclean or mingw32-make distclean before running configure again.
Linking the Application to the Static Version of Qt
As an example, this section will build the Plug & Paint example statically.
Once Qt finishes building, build the Plug & Paint application. First we must go into the directory that contains the application:
Run qmake to create a new makefile for the application, and perform a clean build to create the statically linked executable:
You probably want to link against the release libraries, and you can specify this when invoking qmake . Now, provided that everything compiled and linked without any errors, we should have a plugandpaint.exe file that is ready for deployment. To check that the application has the required libraries, copy the executable to a machine that does not have Qt or any Qt applications installed, and run it on that machine.
Remember that if your application depends on compiler specific libraries, these must still be redistributed along with your application. You can check which libraries your application is linking against by using the depends tool. For more information, read the Application Dependencies section.
Since we cannot deploy plugins using the static linking approach, the application we have prepared is incomplete. It will run, but the functionality will be disabled due to the missing plugins. To deploy plugin-based applications we should use the shared library approach.
Shared Libraries
We have two challenges when deploying the Plug & Paint application using the shared libraries approach: The Qt runtime has to be correctly redistributed along with the application executable, and the plugins have to be installed in the correct location on the target system so that the application can find them.
Building Qt as a Shared Library
For this example, we assume that Qt is installed as a shared library, which is the default when installing Qt, in the C:\path\to\Qt directory.
Linking the Application to Qt as a Shared Library
After ensuring that Qt is built as a shared library, we can build the Plug & Paint application. First, we must go into the directory that contains the application:
Now run qmake to create a new makefile for the application, and do a clean build to create the dynamically linked executable:
This builds the core application, the following will build the plugins:
If everything compiled and linked without any errors, we will get a plugandpaint.exe executable and the pnp_basictools.dll and pnp_extrafilters.dll plugin files.
Creating the Application Package
To deploy the application, we must make sure that we copy the relevant Qt DLLs (corresponding to the Qt modules used in the application) and the Windows platform plugin, qwindows.dll , as well as the executable to the same directory tree in the release subdirectory.
In contrast to user plugins, Qt plugins must be put into subdirectories matching the plugin type. The correct location for the platform plugin is a subdirectory named platforms . Qt Plugins section has additional information about plugins and how Qt searches for them.
If dynamic OpenGL is used, you additionally need to include the libraries required for ANGLE and software rendering. For ANGLE, both libEGL.dll and libGLESv2.dll from Qt’s lib directory are required as well as the HLSL compiler from DirectX. The HLSL compiler library, d3dcompiler_XX.dll, where XX is the version number that ANGLE (libGLESv2) was linked against.
If Qt was configured to link against ICU or OpenSSL, the respective DLL’s need to be added to the release folder, too.
Note: Qt WebEngine applications have additional requirements that are listed in Deploying Qt WebEngine Applications.
Remember that if your application depends on compiler specific libraries, these must be redistributed along with your application. You can check which libraries your application is linking against by using the depends tool. For more information, see the Application Dependencies section.
We’ll cover the plugins shortly, but first we’ll check that the application will work in a deployed environment: Either copy the executable and the Qt DLLs to a machine that doesn’t have Qt or any Qt applications installed, or if you want to test on the build machine, ensure that the machine doesn’t have Qt in its environment.
If the application starts without any problems, then we have successfully made a dynamically linked version of the Plug & Paint application. But the application’s functionality will still be missing since we have not yet deployed the associated plugins.
Plugins work differently to normal DLLs, so we can’t just copy them into the same directory as our application’s executable as we did with the Qt DLLs. When looking for plugins, the application searches in a plugins subdirectory inside the directory of the application executable.
So to make the plugins available to our application, we have to create the plugins subdirectory and copy over the relevant DLLs:
An archive distributing all the Qt DLLs and application specific plugins required to run the Plug & Paint application, would have to include the following files:
Component | File Name | |
---|---|---|
The executable | plugandpaint.exe | |
The Basic Tools plugin | plugins\pnp_basictools.dll | |
The ExtraFilters plugin | plugins\pnp_extrafilters.dll | |
The Qt Windows platform plugin | platforms\qwindows.dll | |
The Qt Windows Vista style plugin | styles\qwindowsvistastyle.dll | |
The Qt Core module | Qt5Core.dll | |
The Qt GUI module | Qt5Gui.dll | |
The Qt Widgets module | Qt5Widgets.dll |
Other plugins might be required depending on the features the application uses ( iconengines , imageformats ).
In addition, the archive must contain the following compiler specific libraries (assuming Visual Studio 14.0 (2015) or 15.0 (2017) or 16.0 (2019)):
Component | File Name | |
---|---|---|
The C run-time | vccorlib140.dll , vcruntime140.dll | |
The C++ run-time | msvcp140.dll |
If dynamic OpenGL was used, then the archive must additionally contain:
Component | File Name | |
---|---|---|
ANGLE libraries | libEGL.dll, libGLESv2.dll | |
HLSL compiler library for ANGLE | d3dcompiler_XX.dll | |
OpenGL Software renderer library | opengl32sw.dll |
Finally, if Qt was configured to use ICU, the archive must contain:
File Name | ||
---|---|---|
icudtXX.dll | icuinXX.dll | icuucXX.dll |
To verify that the application now can be successfully deployed, you can extract this archive on a machine without Qt and without any compiler installed, and try to run it.
An alternative to putting the plugins in the plugins subdirectory is to add a custom search path when you start your application using QCoreApplication::addLibraryPath() or QCoreApplication::setLibraryPaths().
One benefit of using plugins is that they can easily be made available to a whole family of applications.
It’s often most convenient to add the path in the application’s main() function, right after the QApplication object is created. Once the path is added, the application will search it for plugins, in addition to looking in the plugins subdirectory in the application’s own directory. Any number of additional paths can be added.
Manifest files
When deploying an application compiled with Visual Studio, there are some additional steps to be taken.
First, we need to copy the manifest file created when linking the application. This manifest file contains information about the application’s dependencies on side-by-side assemblies, such as the runtime libraries.
The manifest file needs to be copied into the same folder as the application executable. You do not need to copy the manifest files for shared libraries (DLLs), since they are not used.
If the shared library has dependencies that are different from the application using it, the manifest file needs to be embedded into the DLL binary. Since Qt 4.1.3, the following CONFIG options are available for embedding manifests:
Both options are enabled by default. To remove embed_manifest_exe , add
to your .pro file.
You can find more information about manifest files and side-by-side assemblies at the MSDN website.
The correct way to include the runtime libraries with your application is to ensure that they are installed on the end-user’s system.
To install the runtime libraries on the end-user’s system, you need to include the appropriate Visual C++ Redistributable Package (VCRedist) executable with your application and ensure that it is executed when the user installs your application.
They are named vcredist_x64.exe (64-bit) or vcredist_x86.exe (32-bit) and can be found in the folder /VC/redist/ .
Alternatively, they can be downloaded from the web, for example vcredist_x64.exe for Visual Studio 2015.
Note: The application you ship must be compiled with exactly the same compiler version against the same C runtime version. This prevents deploying errors caused by different versions of the C runtime libraries.
Application Dependencies
Additional Libraries
Depending on configuration, compiler specific libraries must be redistributed along with your application.
For example, if Qt is built using ANGLE, its shared libraries and the HLSL compiler from DirectX to be shipped as well.
You can check which libraries your application is linking against by using the Dependency Walker tool. All you need to do is to run it like this:
This will provide a list of the libraries that your application depends on and other information.
When looking at the release build of the Plug & Paint executable ( plugandpaint.exe ) with the depends tool, the tool lists the following immediate dependencies to non-system libraries:
Qt | VC++ 14.0 (2015) | MinGW |
---|---|---|
|
|
|
When looking at the plugin DLLs the exact same dependencies are listed.
From Qt version 5.2 onwards, the officially supported version for OpenSSL is 1.0.0 or later. Versions >= 0.9.7 and qwindows.dll . This file must be located within a specific subdirectory (by default, platforms ) under your distribution directory. Alternatively, it is possible to adjust the search path Qt uses to find its plugins, as described below.
Your application may also depend on one or more Qt plugins, such as the print support plugin, the JPEG image format plugin or a SQL driver plugin. Be sure to distribute any Qt plugins that you need with your application. Similar to the platform plugin, each type of plugin must be located within a specific subdirectory (such as printsupport , imageformats or sqldrivers ) within your distribution directory.
As of Qt 5.14, the libraries are relocatable unless Qt was built with the configure switch -relocatable turned off. The search paths for Qt plugins are relative to the location of the QtCore library and no further steps are required to ensure plugins are found after installing the application on the target machine.
Ensuring Plugins Are Found when Using Non-Relocatable Builds
For non-relocatable builds, additional steps must be taken to ensure plugins are found after the application has been installed on the target machine.
In this case, the search path for Qt plugins is hard-coded into the QtCore library. By default, the plugins subdirectory of the Qt installation is the first plugin search path. However, pre-determined paths like the default one have certain disadvantages. For example, they may not exist on the target machine. For that reason, you need to examine various alternatives to make sure that the Qt plugins are found:
- Using qt.conf . This approach is the recommended if you have executables in different places sharing the same plugins.
- Using QApplication::addLibraryPath() or QApplication::setLibraryPaths(). This approach is recommended if you only have one executable that will use the plugin.
- Using a third party installation utility to change the hard-coded paths in the QtCore library.
If you add a custom path using QApplication::addLibraryPath it could look like this:
Then QCoreApplication::libraryPaths() would return something like this:
- C:/customPath/plugins
- C:/Qt/%VERSION%/plugins
- E:/myApplication/directory
The executable will look for the plugins in these directories and the same order as the QStringList returned by QCoreApplication::libraryPaths(). The newly added path is prepended to the QCoreApplication::libraryPaths() which means that it will be searched through first. However, if you use QCoreApplication::setLibraryPaths(), you will be able to determine which paths and in which order they will be searched.
The How to Create Qt Plugins document outlines the issues you need to pay attention to when building and deploying plugins for Qt applications.
В© 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. Qt and 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.