在命令行構建工程

This page explains how to configure and build existing projects. If you want to know how to create a Qt-based CMake project, see the documentation on how to get started with CMake .

To build a Qt project, CMake needs to know where the Qt installation is located. Usually this is done by setting the CMake variable CMAKE_PREFIX_PATH to Qt's installation prefix. If you are cross-compiling, see 交叉編譯 for details on additional variables you will need to set.

If Qt is installed using Qt Online Installer, choose a Qt version within the top-level installation directory. For example, the following command shows how this is done on Windows:

cmake -DCMAKE_PREFIX_PATH=C:\Qt\6.8.5\msvc2022_64 -S <source-dir> -B <build-dir>
					

The <source-dir> and <build-dir> placeholders represent the source and build directories of your project.

CMake 生成器

CMake 生成必要的構建係統文件,使構建工具 (譬如 GNU Make 或 Ninja) 能夠構建您的工程。

CMake 的默認生成器從屬平颱和構建環境。例如在 Windows,CMake 生成 Visual Studio 工程文件若檢測到 Visual Studio 環境。

為在所有平颱獲得一緻開發體驗,請使用 Ninja or Ninja Multi-Config generator.

You can select the CMake generator either by setting the CMAKE_GENERATOR environment variable or using the -G 自變量:

cmake -G Ninja ...
					

qt-cmake

The qt-cmake script is a convenient alternative to configure your project. It eliminates the need for you to specify the CMAKE_PREFIX_PATH 。可以找到它在 bin directory of your Qt installation prefix. The script passes all parameters to CMake, so you can use it just like you would use cmake :

C:\Qt\6.8.5\msvc2022_64\bin\qt-cmake -G Ninja -S <source-dir> -B <build-dir>
					

在生成構建係統文件後,工程的構建就緒:

cd <build-dir>
ninja
					

You can also use the generator-independent CMake command:

cmake --build <build-dir>
					

交叉編譯

為異於開發機器的平颱構建工程,稱為交叉編譯。例如在 Windows 機器 (主機平颱) 為 Android (目標平颱) 構建。

采用 CMake 交叉編譯要求 toolchain file for most platforms. It also requires a Qt version for the development host, in addition to a Qt version for the target platform. For example, you need Qt for Windows and Qt for Android installed to cross-compile for Android on Windows.

使用 qt-cmake from the Qt installation for the target platform, to cross-compile your project for that platform:

<target-qt>/bin/qt-cmake -S <source-dir> -B <build-dir>
					

This will configure your project for the target platform. The toolchain file is automatically passed, and possibly other platform-specific variables are set up.

指定自定義工具鏈文件

The qt-cmake script passes a Qt-internal toolchain file to CMake. This toolchain file sets several variables that are specific to Qt's target platform.

若正使用的 Qt 安裝尚未在您的機器中構建, qt-cmake needs to know the location of the CMake toolchain file for the target platform.

在這種情況下,可以指導 qt-cmake to chainload a custom toolchain file by setting the QT_CHAINLOAD_TOOLCHAIN_FILE 變量:

~/Qt/6.8.5/android_armv7/bin/qt-cmake -DQT_CHAINLOAD_TOOLCHAIN_FILE=<file-path> -S <source-dir> -B <build-dir>
					

This instructs Qt's internal toolchain file to load your custom toolchain file as well.