QT 6.2 msvc 2019 下 静态编译
环境准备
QT 6 版本全面换成了 CMake,Win 下环境需要
CMake, Ninja, Perl, Python 官网要求
Tool | Supported Versions | Description |
---|---|---|
CMake | Version 3.16 and newer (3.17 and newer for -debug-and-release builds 3.21 and newer for -static builds). |
Required for configuring the Qt build. Available in the Qt Online Installer and on cmake.org. |
Ninja | - | Recommended tool for building Qt. Available in the Qt Online Installer and on ninja-build.org. |
Perl | - | Required build tool. Popular Windows installers are ActiveState Perl and Strawberry Perl. Perl is also installed as part of Git. |
Python | Version 3 | Required build tool. Windows installers are available on python.org, or from the Microsoft Store. |
关于 Perl 个人推荐 Strawberry Perl 版本新,安装方便。缺工具就去下,全部环境变量中配置好就行
编译环境选择:MinGW/MSVC
在 Windows 上,有两个预构建环境可供选择:一个是 MinGW ,另一个是 Microsoft Visual Studio(MSVC)。这两个环境不兼容,无法混合。你必须选择一个。
这两者的区别如下:
当你的项目使用 MinGW 编译的使用,想要用一个 MSVC 编译生成的库时就会有问题。使用 MinGW 编译项目的时候,所使用的 Lib 也要是 MinGW 编译的。如果你只是开发 Window 平台的软件时,最好用 Qt MSVC 组合,这样可以使用大量的第三方 lib,还有很多的构建指令,毕竟 window 上 MSVC 才是王道。
我选择 MSVC,打开安装 VS 时自带安装的 MSCV:x64 Native Tools Command Prompt for VS 2019
不要使用 Developer Command Prompt for VS 2019
编译
在随便什么盘里新建一个目录用来存放编译好的内容:D:\qt
在x64 Native Tools Command Prompt for VS 2019
的终端进入 Qt 源代码目录:
1 | C:\Users\peter\Downloads>cd qt-everywhere-src-5.15.0 |
(不推荐,可跳过)1.修改源码里的qtbase\mkspecs\common\msvc-desktop.conf
文件
qtbase\mkspecs\common\msvc-desktop.conf
文件修改-MD 为-MT
修改前:
1 | QMAKE_CFLAGS_RELEASE = $$QMAKE_CFLAGS_OPTIMIZE -MD |
修改后:
1 | QMAKE_CFLAGS_RELEASE = $$QMAKE_CFLAGS_OPTIMIZE -MT |
D 的意思是动态编译(dynamic link),T 的意思是静态编译(static link)。 这一步官方教程没有要求
目的仅有让编译出来的 Win 上静态文件是最小的(不推荐使用)会导致 example 等动态链接的库无法使用编译好的静态 QT 编译
配置 config 文件:
主要需要在 VS 2019 的命令行中运行,如果一次配置不通过,出错下一次也是无法通过的,因为有CMakeCache.txt
文件,需要删除上一步失败的CMakeCache.txt
文件
我的配置文件:
1 | configure.bat -static -prefix "D:\qt" -confirm-license -opensource -debug-and-release -platform win32-msvc -optimize-size -no-pch -nomake examples -nomake tests -nomake tools -plugin-sql-sqlite -plugin-sql-odbc -qt-zlib -qt-libpng -qt-freetype -qt-pcre -qt-harfbuzz -qt-libjpeg -opengl desktop -mp |
具体含义如下:
1 | configure.bat |
如果无报错
接着运行
1 | cmake --build . ---parallel //编译本目录,parallel为并行,即多核心编译 |
配置 QtCreator
Qt version 下找到刚才编译的bin/qmake.exe
Kits 下选择刚才的 Qt version 注意编译器选择需要和上面编译时使用的一样
至此,编译完成
测试大小
选择 release 模式编译,等待编译完成后打开编译文件夹,即可看到编译后的文件大小大约 12.7MB
如果是动态编译,再使用windeployqt
个人测试的大小是 78MB 左右,所以还是静态编译时省事
参考
最后感谢这些文章的作者,Thanks
Qt5.15 在 Windows 环境静态编译安装和部署的完整过程 VS 2019-Qt static link build Windows 64 bit
使用 MSVC2019 静态编译生成 Qt 库
At last, let’s build Qt statically