Windows qt static build windows

En
Ar
Bg
De
El
Es
Fa
Fi
Fr
Hi
Hu
It
Ja
Kn
Ko
Ms
Nl
Pl
Pt
Ru
Sq
Th
Tr
Uk
Zh

WARNING

The information on this page is outdated!

Please refer to the official documentation for instructions how to build Qt on Windows: https://doc.qt.io/qt-6/windows-building.html

Also, the rationale why to use a static build is questionable. See https://doc.qt.io/qt-6/windows-deployment.html for how to deploy a Qt application on Windows.

If you still want a static build, add

to the

arguments.

Why a static Qt?

On Windows, the pre-built environments from qt.io are dynamically linked. This means that your Qt application dynamically references the Qt DLL’s which are installed with the pre-built environment.

This is probably the preferred environment for developing and debugging since everything is there and ready to use. However, when it comes to deploying an application on systems without pre-installed Qt environments, it becomes complicated. There are several DLL’s to deploy with the application. Even using the classical DLL Dependency Walker tool, you cannot find all required DLL’s since some of them are dynamically loaded at execution. So, when the application is ready to deploy, it is easier to build a static version of it. But building a static version of the application requires a static version of the Qt environment in addition to the pre-built dynamic Qt environment.

This article describes an automated way of downloading, building and installing a static Qt development environment using a Windows PowerShell script.

Note that building and installing a static version of Qt on Windows was somewhat problematic up to Qt 4. But Qt 5 has now a much better support for static builds on Windows and this article takes advantage of that.

MinGW vs. MSVC

On Windows, two pre-built environments can be downloaded: one using MinGW and one using Microsoft Visual Studio. The two environments are incompatible and cannot be mixed. You have to choose one.

This article describes how to build a static version of Qt in a MinGW environment. If you need a static Qt for MSVC, you may probably find some ideas here but there is definitely some extra work.

Target environment

When you develop Qt applications on Windows and need to deploy them later on «general purpose» Windows machines, the recommended Qt environment contains two distinct builds of the same version of Qt:

  • A dynamic version, installed in C:\Qt from a pre-built package.
  • A static version, installed in C:\Qt\Static using the procedure which is described in this article.

The pre-built dynamic environment shall be used for development and debugging. In addition to the Qt command line tools (qmake, moc, uic, lupdate, lrelease, etc.), it contains the high-level GUI tools such as Qt Creator, Assistant, Linguist, etc. The installation is straightforward, everything is here, well integrated, working like a charm.

The static environment should only be used to release the deployment version of the application, after it has been fully developed and debugged using the dynamic environment. The static environment should only be compiled to contain the Qt command line tools. There are at least two reasons for not building static versions of the GUI tools. First, releasing a new version of an application is typically a task that you automate using a script and there is no need for GUI tools at this stage. Second, it is probably impossible to build a static version of Qt Creator because of the lack of support for plugins in a static environment.

Restrictions in a static environment

Although building a static version of your application makes it easier to deploy, there are some restrictions in a static environment. Be sure to check that your application complies with these constraints before going further.

  1. There are licensing issues in distributing applications embedding Qt code in a static link. See here and here for more details. While you are probably safe if your application is distributed according to the terms of a recognized free and open-source license, you should definitely check the licensing issue for proprietary or closed-source applications.
  2. The application cannot use a dynamic modular approach using plugins. But you cannot both ask for a static environment and for a dynamic loading of your own DLL’s.

Also note the following points:

  • The static executable file of the application is bigger than the dynamic one since all used Qt code is copied into the executable. However, if your application has only one executable, the total deployed size is smaller since only the Qt code which is actually used is linked. When deploying a dynamic version of the application, you have to install all required Qt DLL’s with the application and the overall size of all these DLL’s is larger than the static application.
  • A Qt static build means that no Qt or MinGW DLL’s are used. However, the static executable file of the application still references the Windows DLL’s such as kernel32.dll or user32.dll. These DLL’s, however, are installed with Windows and do not need to be deployed with the application.

Prerequisites

Dynamic pre-built Qt environment

You must have a pre-built Qt environment installed before you attempt to build a static version of the library with the Qt source code.

  1. Obtain the Qt Installer from qt.io and install the relevant pre-build Qt environment. For example, «Qt 5.15.2 MinGw 8.1.0 32-bit»
  2. Preferably plan the installation of the same version of Qt for the dynamic and static builds. This is not a strict requirement but it is a safe configuration.
  3. During installation, select the default installation location (C:\). Be sure to add the MinGW environment in the installation (selectable in the «Tools» branch of the installation options).

If you have a separated MinGW environment that you prefer to use and do not install the one from the Qt package installer, be sure to specify the option -MingwDir in the static build script (see below).

Example image of the Qt Installer with what was selected to write this guide.

Windows PowerShell

The script which builds the static Qt environment is a PowerShell script. PowerShell version 3.0 or higher is required. It is recommended to use Windows 10 which comes with PowerShell version 5 and onwards.

7-Zip

The build script also requires 7-Zip to uncompress the downloaded Qt source code. Be sure to install it first.

Qt build dependancies

As per the README that is packaged with the qt-everywhere-* zip package, it is noted that for windows the following also need to be available (as at Qt version 5.15.2):

  • Perl version 5.12 or later (http://www.activestate.com/activeperl/)
  • Python version 2.7 or later (http://www.activestate.com/activepython/)
  • Ruby version 1.9.3 or later (http://rubyinstaller.org/)

Building the Qt static environment

Using the Windows Powershell script

The PowerShell script aims to assist with the install of the qt source code and the compilation of Qt as a static binary. For the purposes of the below instructions, Qt version 5.15.2 is used with Windows 10.

1. Take a copy of the following PowerShell script on github: qt-windows-static-build.ps1

2. Edit the script as required to change the variables which define the Qt version and directory location of the Qt pre-built environment already installed. Specifically the lines:

[CmdletBinding()]
param(
    $QtSrcUrl = "https://download.qt.io/official_releases/qt/5.15/5.15.2/single/qt-everywhere-src-5.15.2.zip",
    $QtStaticDir = "C:\Qt\Static", # NO TRAILING SLASH
    $QtVersion = "5.15.2", #If you change this, you'll need to change the URL above to download as well...
    $MingwDir = "",
    [switch]$NoPause = $false
)

The script contains flags to ‘configure’ what to include in the Qt static build. By default it removes a lot of modules that probably are not required for most applications. However, if your requirements differ — modify this line of the script accordingly.

cmd /c "configure.bat -static -release -platform win32-g++ -opensource -confirm-license -prefix $QtDir -qt-zlib -qt-libpng -qt-webp -qt-libjpeg -qt-freetype  -no-opengl -skip qt3d -skip qtactiveqt -skip qtandroidextras -skip qtcharts -skip qtconnectivity -skip qtdatavis3d -skip qtdeclarative -skip qtdoc -skip qtgamepad -skip qtlocation -skip qtlottie -skip qtmacextras -skip qtmultimedia -skip qtnetworkauth -skip qtpurchasing -skip qtquick3d -skip qtquickcontrols -skip qtquickcontrols2 -skip qtquicktimeline -skip qtremoteobjects -skip qtscript -skip qtsensors -skip qtspeech -skip qtsvg -skip qtwayland -skip qtwebglplugin -skip qtwebview -skip webengine -make libs -nomake tools -nomake examples -nomake tests"

3. Execute the script in Windows PowerShell as a non-administrator user:

.\qt-windows-static-build.ps1

The PowerShell script will check to see if your path variable is configured correctly such that ‘powershell’, ‘ruby’, ‘python’ and ‘perl’ commands are avaialble. If not, you will need to double check what you installed as covered in ‘Qt build dependancies’. The PowerShell will now perform the following steps:

  1. Download the Qt everything source code.
  2. Build a static version of Qt using the MinGW compiler in the pre-built dynamic environment. It builds the libraries and the command line tools (qmake, moc, uic, lupdate, lrelease, etc.)
  3. Install the static version of Qt in C:\Qt\Static by default.

The execution of this script may take a couple of hours to complete, depending on your processing power. So you have to be patient. Qt is a complex framework with a very large amount of code.

Command line syntax

Alternatively, you can invoke the script from the PowerShell prompt using the following syntax:

windows-build-qt-static.ps1 [-QtSrcUrl url] [-QtStaticDir directory] [-QtVersion string] [-MingwDir directory] [-NoPause]

Command line parameters

-QtSrcUrl url

Specify the URL of the Qt source file archive.

-QtStaticDir directory

Specify the root directory where the static versions of Qt are installed. By default: C:.

-QtVersion string

Specify the Qt version. By default, the script tries to extract the version number from the Qt source file name. Usually, this is sufficient, the script will find «5.15.2» or «5.0.0-rc1» for instance. If the naming scheme of the Qt source file changes one day, you may need to specify an explicit value to this parameter.

-MingwDir directory

Specify the root directory of the MinGW environment. By default, use the version which was installed by the prebuilt Qt environment.

When the prebuilt environment for Qt 5.15.2 is installed for instance, the script locates MinGW in C:\Qt\5.15.2\Tools\mingw492_32. If you chose not to install MinGW as part of the prebuilt environment for Qt, you have to specify the root directory of your MinGW installation.

-NoPause

Do not wait for the user to press enter at the end of execution. By default, the scripts executes a pause instruction at the end of execution, which is useful when the script was run from the Windows Explorer.

Using the Qt static environment

Using the Qt static environment with Qt Creator (recommended)

This section describes how to use the static Qt environment from Qt Creator.

Please note: Qt Creator is provided as part of the dynamic pre-built environment. By default, it builds the applications for this dynamic environment, but it is possible to configure projects to use the static Qt environment when required.

The following instructions are based on a standard Qt 5.15.2 / Qt Creator 4.14.2 installation. Change the version numbers to adapt to your configuration.

Qt Creator Configuration

  1. Open the Qt Creator
  2. Tools (menu) -> Option
  3. Select ‘Qt Versions’ tab. In the «qmake location» table, there must be an «Auto-detected» part and a «Manual» part. In the «Auto-detected» part, there should be one line named «Qt 5.15.2 MinGW 32bit C:\Qt\Qt5.15.2\5.5\mingw492_32\bin\qmake.exe» (or whatever version of Qt you are working with). The «Manual» part is initially empty.
  4. Click «Add», browse to C:\Qt\Static\<your static build version>\bin and select «qmake.exe». The version name is automatically set to «Qt 5.15.2 (5.15.2)». You should set a more meaningful name such as «Qt 5.15.2 MinGW Static 32bit»
  5. Then go to tab «Kits». Again, there must be an «Auto-detected» part and an initially empty «Manual» part.
  6. Click «Add».
  7. Set a meaningful name such as «Desktop Qt 5.15.2 MinGW Static 32bit». In the «Qt version» field towards the bottom, select your static environment, named «Qt 5.15.2 MinGW Static 32bit» if you followed the above advice. Qt Creator should auto populate the Compiler details.

Then click «OK» to terminate the options setup.

Your Project Configuration

  1. In each project you want to deploy with a static build, edit the project setup (select «Projects» in the left vertical pane).
  2. Click «Add Kit» in the upper left corner and select your static kit, named «Desktop Qt 5.15.2 MinGW Static 32bit» if you followed the above advice.
  3. The new kit for your project is configured. Note that, by default, there are distinct build directories for the dynamic and static versions of your project.
  4. Now you can build your application in any combination of static vs. dynamic and release vs. debug. In the bottom part of the left pane, the project selector (the computer icon with the name of your project and either «Release» or «Debug») lets you select the combination you want.

Command line

This section describes how to use the static Qt environment from the command line, either the traditional Windows command shell (cmd.exe) or the Windows PowerShell.

Simply add the bin subdirectory of the static Qt environment in front of the Path environment variable. For Qt 5.15.2, this is C:\Qt\Static\5.15.2\bin.

Do not forget to also include the MinGW environment in the path. With the dynamic pre-built Qt environment, you may want to add Qt Creator also.

The following commands summarize the command line setups for the various environments.

Dynamic pre-built Qt with the traditional Windows command shell:

set Path=C:\Qt\5.15.2\mingw81_32\bin;C:\Qt\Tools\mingw810_32\bin;C:\Qt\Tools\QtCreator\bin;C:\Perl64\bin;C:\Ruby27-x64\bin;C:\ActivePython3;

Dynamic pre-built Qt with the Windows PowerShell:

$env:Path=C:\Qt\5.15.2\mingw81_32\bin;C:\Qt\Tools\mingw810_32\bin;C:\Qt\Tools\QtCreator\bin;C:\Perl64\bin;C:\Ruby27-x64\bin;C:\ActivePython3;

Static Qt build with the traditional Windows command shell:

set Path=C:\Qt\Static\5.15.2\bin;C:\Qt\5.15.2\mingw81_32\bin;C:\Qt\Tools\mingw810_32\bin;

Static Qt build with the Windows PowerShell:

$env:Path=C:\Qt\Static\5.15.2\bin;C:\Qt\5.15.2\mingw81_32\bin;C:\Qt\Tools\mingw810_32\bin;

When to use a Static Qt build

It is recommended to only build release versions of the application with at static Qt environment. Avoid building a debug version of the application with the static Qt environment. There are several reasons for this:

  • The recommended environment for the development, debug and test phase is the pre-built dynamic environment, not the static one.
  • The size of a static application in debug mode is insanely huge. For a given application, the following sizes have been observed for the application executable file:
    • Dynamic + Release: 1 MB
    • Dynamic + Debug: 33 MB
    • Static + Release: 16 MB
    • Static + Debug: 297 MB

Доброго времени суток, хабравчане!

Я уверен, что все заметили, когда делали деплой своей программы через 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 ГБ свободного места.

Сам алгоритм:

  1. Переходите в директорию, где папка Src (D:\Qt\5.x.x\Src);
  2. Там создайте папку static (D:\Qt\5.х.х\static);
  3. Папку Src скопируйте в папку static. Получится D:\Qt\5.x.x\static\Src. Дальнейшие действия будут там, в Папке Src;
  4. Создайте папку mingwXX_32 (у меня, например, mingw73_32). Получится D:\Qt\5.x.x\static\mingwXX_32;
  5. Редактируйте файл qmake.conf, который находится в D:\Qt\5.х.х\static\Src\qtbase\mkspecs\win32-g++.

    В самый конец файла, после строки load(qt_config) допишите с новой строки эти команды:

    QMAKE_LFLAGS += -static -static-libgcc
    	   QMAKE_CFLAGS_RELEASE -= O2
               DEFINES += UNICODE QT_STATIC_BUILD

  6. Сохраните файл qmake.conf;
  7. Откройте (ВНИМАНИЕ! НЕ CMD!) командную строку MinGW. В поисковике компьютера (на панели задач) пишите mingw.
    Командная строка MinGW будет выдана как Qt 5.x.x (MinGW x.x.x 32-bit)
  8. Введите в командную строку MinGW поочередно следующие команды:
    set LANG=en

    set QT_INSTALL_PREFIX="C:\Qt\5.8-static\mingw53_32"

    cd /d %QT_INSTALL_PREFIX%\..\Src (именно такая строка без изменений)

    configure.bat -static -debug-and-release -platform win32-g++ -prefix %QT_INSTALL_PREFIX% -qt-zlib -qt-pcre -qt-libpng -qt-libjpeg -qt-freetype -opengl desktop -opensource -confirm-license -make libs -nomake tools -nomake examples -nomake tests -qt-sqlite -no-ssl

    Тут стоит обратить внимание на опцию -no-ssl — это значит что Qt будет собран без поддержки SSL.

    Если никаких ошибок нету, можно продолжать:

  9. Введите mingw32-make -k -j4
    Нереально длительный процесс, можете смело забыть про него на 4 часа ориентировочно, от скорости чтения/записи диска не зависит, а зависит от процессора. Там где -j4 вместо 4 поставьте число ядер вашего процессора.
  10. Введите mingw32-make -k install
    В результате получаем статическое окружение в D:\Qt\5.x.x\statiс\mingwXX_32;
  11. Настройка Qt Creator:
    • В верхнем меню Инструменты -> Параметры -> Профили 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 (название профиля, которое вы указали при добавлении профиля)
    • Применить -> Ок

  12. Остается только пересобрать свой проект с новым комплектом.

Дополнительная информация. У меня:

  • 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

Полет нормальный.

Брал информацию отсюда:

  • vladsol.tk/2017/05/qt-5-8-0-static-build
  • www.pvsm.ru/pesochnitsa/73256

Qt is a cross-platform software development framework for C++ used to build software across all major industries. If you work at company that uses Qt you may have wondered how you can pack all dependencies of your application in a single executable. Yes, that is possible but only with static builds. Let me show you how to do it.

Disclaimer: According to the Qt license you may not deploy static builds with the open-source license. Deploying static builds is only allowed for companies who purchase Qt.

Does this image look familiar to you?

Yeah Qt has so many dependencies… with static builds Qt can generate a single executable file so, no more missing dependencies and no need to use external tools such as Qt’s windeployqt or Dependency Walker.

Unfortunately the only way to do static builds is to compile Qt itself statically first. I’ll show you how to do it and how to setup Qt Creator to do both shared and static builds:

Requirements

  • A computer to develop Qt applications with Qt and Qt Creator already installed;
  • A Windows 10 (64 bit) virtual machine to build a static version of Qt;
  • Qt source code: https://www.qt.io/offline-installers > Offline Installers > Source packages > For Windows users as a single zip file.
  • mingw-w64: https://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win32/Personal%20Builds/mingw-builds/installer/mingw-w64-install.exe/download
  • Perl (64 bit): http://strawberryperl.com/
  • Ruby (64 bit): https://rubyinstaller.org/downloads/
  • Python 2.7: https://www.python.org/downloads/

Setup

In your virtual machine start by unpacking the Qt Source code to the root of the system, for instance C:\qt-everywhere-src-5.14.2. Now install Perl, Python, Ruby and then MinGW with the following settings:

  • Architecture: x86_64
  • Threads: win32
  • Installation path: C:\Qt-Static\mingw-w64

Make sure Perl, Python, Ruby and MinGW are in your system path and MinGW is the first one. This will avoid issues with the build in C compiler of Strawberry Perl. Example:

Compiling Qt Statically

Now that we have all dependencies open command prompt as admin and:

cd C:\qt-everywhere-src-5.14.2
configure -debug-and-release -static -opengl desktop -qt-zlib -qt-pcre -qt-libpng -qt-libjpeg -qt-freetype -nomake examples -nomake tests

This will configure the source code for a static build capable of debug and release configurations. I’ve added OpenGL for desktop applications and most of the commonly used libraries. I’ve also excluded examples and tests – those are already available in our development machine. Now build and install Qt with:

mingw32-make
mingw32-make install

Qt will be installed to C:\Qt\Qt-5.14.2, now you may copy that directory over to our final destination C:\Qt-Static\Qt-5.14.2.

Configure Your Development Machine

Start by copying the static build folder C:\Qt-Static from the virtual machine to the same path in your development machine. Open Qt Creator and go to Tools > Options > Kits.

Now under Compilers add the following:

  • C Compiler:
    • Name: MinGW Static
    • Path: C:\Qt-Static\mingw-w64\mingw64\bin\gcc.exe
  • C++ Compiler:
    • Name: MinGW++ Static
    • Path: C:\Qt-Static\mingw-w64\mingw64\bin\g++.exe

Under Qt Versions add a new version as:

  • Version name: Qt-Static %{Qt:Version} (Qt-5.14.2)
  • qmake location: C:\Qt-Static\Qt-5.14.2\bin\qmake.exe

Now go to Kits and add a Kit that uses the static Qt version and the compiler we’ve added before:

Project Configuration

In order to do static builds you still need to add the following to your project’s .pro file:

# Static Builds
QTPREFIX=$$[QT_INSTALL_PREFIX]
equals(QTPREFIX, "C:/Qt-Static/Qt-5.14.2"){
    message("--STATIC BUILD--")
    CONFIG += qt static
    QMAKE_LFLAGS += -static-libgcc -static-libstdc++
} else {
    message("--NON-STATIC BUILD--")
}

This configuration will detect whenever you’re building with the static Qt and make sure the proper flags are added.

Congratulations, you’re ready for your first static build.

ОС: Windows 11
Microsoft Visual Studio 2022
Qt 6.8.1

1. Скачиваем архив исходников Qt для Windows (qt-everywhere-src-6.8.1.zip) с официального сайта qt.

2. Создаем каталог, например, c:\Qt\Qt6.8.1-x64-msvc2022-static\6.8\Src и распаковываем в него содержимое архива исходников. Сборка в дальнейшем будет привязана к данному каталогу и букве диска. Получим подкаталоги 6.8\Src\qtbase, 6.8\Src\coin и т.д.).

3. Устанавливаем:
Cmake (https://cmake.org/download)
StrawberryPerl (https://strawberryperl.com)
Python 3 (https://www.python.org)
Node.js (https://nodejs.org)
ninja (https://github.com/ninja-build/ninja/releases)

4. Запускаем командную строку (cmd) с правами администратора и последовательно выполняем в ней следующие команды:

Задаем системные переменные Qt:

set QTDIR=c:\Qt\qt6.8.1-x64-msvc2022-static\6.8\Src\qtbase
set PATH=c:\Qt\qt6.8.1-x64-msvc2022-static\6.8\Src\qtbase\bin;%PATH%

Системная переменная пути к LLVM:

set PATH=c:\Program Files\LLVM\bin;%PATH%
set LLVM_INSTALL_DIR=C:\Program Files\LLVM

Системные переменные пути к ninja и gnuwin32 (для QtPdf):

set PATH=c:\Qt\Tools\Ninja;%PATH%
set PATH=c:\Program Files (x86)\GnuWin32\bin;%PATH%

Для Microsoft Visual Studio 2022 (msvc2022):

cd «C:\Program Files\Microsoft Visual Studio\2022\Professional\VC\Auxiliary\Build»
vcvarsall.bat amd64

Конфигурация:

configure -debug-and-release -static -static-runtime -opensource -confirm-license -platform win32-msvc -nomake examples -nomake tests -qt-zlib -qt-libpng -qt-libjpeg -prefix «c:\Qt\qt6.8.1-x64-msvc2022-static\6.8» -skip qtandroidextras -skip qtactiveqt -skip qtgamepad -skip qtmacextras -skip qtlocation -skip qtlottie -skip qtquick3d -skip qtquick3dphysics -skip qtquickcontrols -skip qtquickcontrols2 -skip qtquickeffectmaker -skip qtquicktimeline -skip qtremoteobjects -skip qtscript -skip qtscxml -skip qtsensors -skip qtspeech -skip qtvirtualkeyboard -skip qtwayland -skip qtwebengine -skip qtx11extras -no-dbus -no-openssl -skip qtgraphs -skip qdoc

где:

-prefix «c:\Qt\qt6.8.1-x64-msvc2022-static\6.8» — путь, куда будет помещена сборка,
Пропущенные модули: -skip qtandroidextras -skip qtactiveqt -skip qtgamepad -skip qtmacextras -skip qtlocation -skip qtlottie -skip qtquick3d -skip qtquick3dphysics -skip qtquickcontrols -skip qtquickcontrols2 -skip qtquickeffectmaker -skip qtquicktimeline -skip qtremoteobjects -skip qtscript -skip qtscxml -skip qtsensors -skip qtspeech -skip qtvirtualkeyboard -skip qtwayland -skip qtwebengine -skip qtx11extras -skip qtgraphs -skip qdoc
-nomake examples -nomake tests — отказ от сборки тестов и примеров
-platform win32-msvc — выбор платформы
-confirm-license — подтверждение согласия с лицензией
-static -static-runtime — статическая сборка

Переход в каталог сборки:

cd c:\Qt\qt6.8.1-x64-msvc2022-static\6.8\Src

Сборка:

cmake —build . —parallel

Установка:

cmake —install .

Сборка и установка документации (не прошло):

cmake —build . —target docs
cmake —build . —target install_docs

После сборки каталог Src можно удалить, там лежат исходники и более 100 Гигабайт промежуточных файлов.

Возможные ошибки:

  • QtPdf won’t be built. Python3 html5lib is missing. Необходимо установить html5lib:

pip install html5lib

QtPdf won’t be built. Tool gperf is required.
QtPdf won’t be built. Tool bison is required.
QtPdf won’t be built. Tool flex is required.
Необходимо установить:
Gperf (https://sourceforge.net/projects/gnuwin32/files/gperf/3.0.1/gperf-3.0.1.exe/download)
Flex (https://gnuwin32.sourceforge.net/downlinks/flex.php)
Bison (http://downloads.sourceforge.net/gnuwin32/bison-2.4.1-setup.exe)

После сборки каталог Src будет занимать больше 100 Гигабайт. Его можно будет удалить.

QDoc собрать статически не удалось.

QtWebengine не поддерживает статическую сборку.

LLVM с официального сайта не подходит для данной статической сборки. Будет всё равно выводиться предупреждение.
Оказывается необходимо выбрать с сайта qt (https://qt-mirror.dannhauer.de/development_releases/prebuilt/libclang/) определенную версию LLVM (собранную разработчиками Qt) со статическими библиотеками, которых нет в официальной версии LLVM. Мне это сделать не удалось: выводились ошибки при сборке самого Qt6.

Поддержать проект (подарком):
ЮMoney 4100 1188 9778 9041
карта 5599 0021 0667 6341

Статическая сборка на основе Qt 5.15.1 MinGWx64 в Windows 10

1. Запускаем qt-unified-windows-x86-4.2.0-online.exe

  • Cкачать с сайта Qt

Qt устанавливать нужно на диск C

2. Запускаем установшики Python, Perl, Ruby (64 битные версии)

Cкачать последнюю версию с сайтов производителей:

  • Python x64
  • Perl x64
  • Ruby x64 (WITHOUT DEVKIT)

Дальше нужно установить(Устанавливать нужно на диск C):

  • Python
  • Perl
  • Ruby

3. Добавляем пути к программам и библиотекам в параметры системы:

Поиск:arrow_right:Система:arrow_right:Дополнительные параметры системы:arrow_right:Параметры среды:arrow_right:Системные переменные:arrow_right:Path:arrow_right:Изменить

  • Создаём пути

4. Далее скачиваем исходник QT 5.15.1

  • Cкачать с сайта Qt

Разархивируйте его в папку Qt, для удобства создайте папку Src и разархивируйте туда

  • Должно получиться вот так, после разахивирования

C:\Qt\Src\qt-everywhere-src-5.15.1\

5. Запускаем cmd и переходим в папку

C:\Qt\Src\qt-everywhere-src-5.15.1\

  • Команды для командной строки:
C:\Users\Cereg>cd..
C:\Users>cd..
C:\>cd Qt
C:\Qt>cd Src
C:\Qt\Src>cd qt-everywhere-src-5.15.1
C:\Qt\Src\qt-everywhere-src-5.15.1>
  • В Командную строку вставляем это команду:

configure -static -debug-and-release -platform win32-g++ -qt-zlib -qt-pcre -qt-libpng -qt-libjpeg -qt-freetype -opengl desktop -no-angle -no-openssl -opensource -confirm-license -make libs -nomake tools -nomake examples -nomake tests -prefix C:\Qt\5.15.1\mingw81_64_static

  • После завершения проверки вставляем это команду:

mingw32-make -k -j16
(16 это количество ядер на компьютере)

  • После завершения вставляем это команду:

mingw32-make -k install

ВЫПОЛНЕНИЕ МОЖЕТ ПРОХОДИТЬ ОЧЕНЬ ДОЛГО (4-6 ЧАСОВ), ВСЕ ЗАВИСИТ ОН МОЩНОСТЬИ ВАЩЕГО КОМПЬЮТЕРА , И ОТ КОЛИЧЕСТВА БИБЛИОТЕК КОТОРЫЕ ВАМ НУЖНЫ

6. После завершения процедуры переходим в Qt Creator и запускаем какой-то проект

  • Переходим в:

Проекты:arrow_right:Управление:arrow_right:Профили Qt:arrow_right:Добавить

  • Добавляем qmake.exe и для удобства называем Qt (5.15.1) static

5


ЕСЛИ НЕ ХВАТАЕТ КАКОЙ-ТО БИБЛИОТЕКИ ИЛИ ФАЙЛА (ЭТО БУДЕТ НАПИСАНО ПОД qmake path), ТО ПЕРЕХОДИМ В

C:\Qt\5.15.1\mingw81_64\bin

И КОПИРУЕМ НЕОБХОДИМЫЕ ФАЙЛЫ(ФАЙЛЫ С ОДИНАКОВЫМ НАЗВАНИЕМ) В

C:\Qt\5.15.1\mingw81_64_static\bin(БЕЗ ЗАМЕНЫ)


  • Переходим в:

Проекты:arrow_right:Управление:arrow_right:Комплекты:arrow_right:Добавить

  • Добавляем новую сборку

6

  • Переходим в Проекты, и добавляем сборку в проект, нажать на зеленый плюсик

7

  • Переходим в .pro файл и добавляем строку

QMAKE_LFLAGS_RELEASE += -static -static-libgcc

  • И собираем проект для релиза

ЕСЛИ ВЫЛЕТАЮТ ОШИБКИ: cannot found -ltiff, cannot found -lwebp

Можно взять библиотеку tiff из этого репозитория или скачать

Можно взять библиотеку webp из этого репозитория или скачать

  • Нужно в папку C:\Qt\Tools\ добавить библиотеки
  • Разархивируйте их в папку C:\Qt\Tools\ и переменуйте папки в lift и libwebp
  • И добавляем пути в систему, как в пункте 3
  • Повторяем 5 пукнт и добавляем в команду -qt-tiff -qt-webp, полная команду будет выглядить так:

configure -static -debug-and-release -platform win32-g++ -qt-zlib -qt-pcre -qt-libpng -qt-tiff -qt-webp -qt-libjpeg -qt-freetype -opengl desktop -no-angle -no-openssl -opensource -confirm-license -make libs -nomake tools -nomake examples -nomake tests -prefix C:\Qt\5.15.1\mingw81_64_static

  • И заново создаем сборщик, как в пункте 5

НО ЕСТЬ ГОТОВЫЙ СКОМПИЛИРОВАННЫЙ mingw81_64_static.rar

7. Документация QT

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как отключить ввод пароля при запуске windows 10 на ноутбуке
  • Hp 1132 mfp драйвер windows 10 64 не устанавливается
  • Зачем нужна лицензионная windows
  • Как вызвать калькулятор в windows 10 на клавиатуре горячие клавиши
  • Не удалось инициализировать аварийный дамп windows 10