Автоматизация сборки qt проекта на windows в travis ci

Configuring and Building

The Qt5 build system should be fairly resilient against any «outside distractions» — it shouldn’t matter whether you have other Qt versions in PATH, and QTDIR is entirely ignored. However, make sure that you have no qmake-specific environment variables like QMAKEPATH or QMAKEFEATURES set, and the qmake -query output does not refer to any other Qt versions ($HOME/.config/Qt/QMake.conf should be empty).

Note: To build qdoc and Qt documentation in future you should set LLVM_INSTALL_DIR environment variable pointing to directory where LLVM is installed (it should be top level directory, the configuration scripts use relative path tracing from this directory). For example, in Linux with LLVM installed in isolated directory (/usr/llvm), at a bash prompt:

$ export LLVM_INSTALL_DIR=/usr/llvm

For Linux / macOS, to install in ~/qt5-build (an arbitrary name), assuming you are in ~:

$ mkdir qt5-build
$ cd qt5-build
$ ../qt5/configure -developer-build -opensource -nomake examples -nomake tests

For Windows, again assuming you are in ~:

$ mkdir qt5-build
$ cd qt5-build
$ ..\\qt5\configure -developer-build -opensource -nomake examples -nomake tests

The -developer-build option causes more symbols to be exported in order to allow more classes and functions to be unit tested than in a regular Qt build. It also defaults to a ‘debug’ build, and installs the binaries in the current directory, avoiding the need for ‘make install’. ‘-opensource’ sets the license to be GPL/LGPL. The -nomake examples and -nomake tests parameters make sure examples and tests aren’t compiled by default. You can always decide to compile them later by hand.

Some Hints

  1. You can add -confirm-license to get rid of the question whether you agree to the license.
  2. On Windows, you might not be able to build if sh.exe is in your PATH (for example due to a git or msys installation). Such an error is indicated by qt5-src\qtbase\bin\qmake.exe: command not found and alike. In this case, make sure that sh.exe is not in your path. You will have to re-configure if your installation is already configured.

Now trigger the build from within the build directory by running:

$ make -j$(nproc)

For Windows (MSVC), choose one of the following, depending on your setup/environment:

$ nmake

or

$ jom

or

$ mingw32-make

Or only build a specific module, e.g. declarative, and modules it depends on:

$ make module-qtdeclarative

Windows

The tools bison, flex and gperf which are required for building are provided for convenience in the folder gnuwin32\bin. If you are using shadow builds, you must add this directory to your PATH, else no special actions need to be done manually in order to use them.

Дисклеймер

В данной статье приводятся данные о занимаемой программой памяти при использовании различных инструментов, фреймворков и библиотек для создания GUI на Linux. Все измерения сделаны на одном и том же компьютере с Ubuntu 19.04 (Disco Dingo) x86_64 с помощью программы Ksysguard, предоставляющей данные о потребляемой приложениями собственной памяти. Я не переустанавливал систему специально для проведения теста. Он был выполнен на моей повидавшей виды Ubuntu, на которой уже были установлены разного рода пакеты, что могло повлиять/исказить результаты.

Для некоторых инструментов я даже добавил измерения, полученные на Windows 10, которые вряд ли можно сравнивать с линуксовскими, но посмотреть интересно.

Хочу заметить, что мои измерения не представляют научной ценности. Имея другие исходные данные, вы можете получить совершенно другие результаты.

Переменные

В проектном файле, переменные используются для хранения списка строк. В простейшем проекте, эти переменные информируют

qmake

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

qmake ищет эти переменные в каждом проектном файле, и используется содержимой для определения того, что должно быть записано в

Makefile.

Например, список значений в переменных

HEADERS

и

SOURCES

используются для уведомления qmake об исходных и заголовочных файлах в некоторых директориях.

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

Присваивание списка значений переменной:

HEADERS = mainwindow.h paintwidget.h

Список значений переменных расширяется следующим образом:

SOURCES = main.cpp mainwindow.cpp \
          paintwidget.cpp
CONFIG += console

Примечание:

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

HEADERS.

Второе объявление разделяет значения как в переменной

SOURCES

через обратный слеш («\»).

Переменная

CONFIG

является другой специальной переменной, которая используется qmake, когда генерируется Makefile.

SUBDIRS projects

SUBDIRS is a powerful method for breaking projects into smaller chunks. It’s actually much more powerful than is indicated in the documentation, though.

There are three different possible meanings of the values in the SUBDIRS variable. They can be directories, like the manual indicates; in this case, qmake will look for a .pro file with the same name as the directory. It can also be a .pro file, with or without a path, in which case it will go directly to that file. Or most powerfully, it can be a variable. In this case, one configures behaviour via compound variables, using the following keywords:

  • subdir — the path to the .pro file. This will behave as if you simply specified the directory.
  • file — the .pro file itself. This will behave as if you specified the full path and filename.
  • depends — a list of other SUBDIRS entries that this entry depends on.
  • makefile — it seems this sets the name of the makefile that will be generated and called for this target.
  • target — this sets the target within the makefile that will be called. (Probably most useful in combination with the «makefile» option.)

For example:

TEMPLATE = subdirs
SUBDIRS = sub_lib sub_tests sub_app

sub_lib.subdir = lib
sub_tests.file = tests/proj.pro
sub_tests.depends = sub_lib
sub_app.subdir = app
sub_app.depends = sub_lib

This makes it possible to use make -j 4 on your fancy quad-core system with a project that consists of several components that depend on each other. To simplify the process a bit, the following test function can be defined:

# addSubdirs(subdirs,deps): Adds directories to the project that depend on
# other directories
defineTest(addSubdirs) {
    for(subdirs, 1) {
        entries = $$files($$subdirs)
        for(entry, entries) {
            name = $$replace(entry, , _)
            SUBDIRS += $$name
            eval ($${name}.subdir = $$entry)
            for(dep, 2):eval ($${name}.depends += $$replace(dep, , _))
            export ($${name}.subdir)
            export ($${name}.depends)
        }
    }
    export (SUBDIRS)
}

You can then use it like

addSubdirs (contrib/*)

addSubdirs (src/lib/kernel, contrib/module1 contrib/module2)
addSubdirs (src/lib/gui, src/lib/kernel contrib/module3 contrib/module4)

addSubdirs (src/tests/kernel, src/lib/kernel)
addSubdirs (src/tests/gui, src/lib/gui)

addSubdirs (src/main, src/lib/gui src/lib/kernel)

addSubdirs (src/modules/*, src/lib/kernel)

to define a project that has:

  • several contributed modules that should be compiled first
  • a kernel lib for non-gui related stuff that depends on some contrib modules
  • a gui lib that depends on the kernel lib and some other contrib modules
  • test benches for the kernel and gui libs
  • a main program that uses the gui and kernel libs
  • several modules that only depend on the kernel lib
  • and that compiles in parallel where possible.

Operating Modes

qmake supports two different modes of operation. In the default mode, qmake uses the information in a project file to generate a Makefile, but it is also possible to use qmake to generate project files. If you want to explicitly set the mode, you must specify it before all other options. The can be either of the following two values:

  • qmake output will be a Makefile.
  • qmake output will be a project file.

    Note: It is likely that the created file will need to be edited. For example, adding the variable to suit what modules are required for the project.

You can use the to specify both general and mode-specific settings. Options that only apply to the Makefile mode are described in the section, whereas options that influence the creation of project files are described in the section.

Environment setup

It looks good to have a script to set up the environment instead of setting it all using system PATH variable:

@ECHO OFF

set DEV=Cset QTDIR=%DEV%set PATH=%SystemRoot%;%SystemRoot%32;%QTDIR%

echo Setting OpenSSL Env.
set OPENSSL=%DEV%set PATH=%OPENSSL%;%PATH%
set LIB=%OPENSSL%set INCLUDE=%OPENSSL%

echo Setting NASM Env.
set PATH=%DEV%;%PATH%

echo Setting DirectX Env.
set LIB=%DEV%SDK\Lib\x86;%LIB%
set INCLUDE=%DEV%SDK\Include;%INCLUDE%

echo Setting Windows SDK Env.
set WindowsSdkDir=%DEV%7.1 SDK
set PATH=%WindowsSdkDir%;%PATH%
set LIB=%WindowsSdkDir%;%LIB%
set INCLUDE=%WindowsSdkDir%;%INCLUDE%
set TARGET_CPU=x86

echo Setting MSVC2010 Env.
set VSINSTALLDIR=%DEV%set VCINSTALLDIR=%DEV%set DevEnvDir=%VSINSTALLDIR%7\IDE
set PATH=%VCINSTALLDIR%;%VSINSTALLDIR%7\Tools;%VSINSTALLDIR%7\IDE;%VCINSTALLDIR%;%PATH%
set INCLUDE=%VCINSTALLDIR%;%INCLUDE%
set LIB=%VCINSTALLDIR%;%LIB%
set LIBPATH=%VCINSTALLDIR%

echo Setting Framework Env.
set FrameworkVersion=v4.0.30319
set Framework35Version=v3.5
set FrameworkDir=%SystemRoot%.NET\Framework
set LIBPATH=%FrameworkDir%amp;#37;FrameworkVersion%;%FrameworkDir%amp;#37;Framework35Version%;%LIBPATH%
set PATH=%LIBPATH%;%PATH%

echo Env. ready.

title Qt Framework 4.7.1 Development Kit.

cd %DEV%

This file is .bat (or.cmd) script. Just modify and save it for your environment. I set it up from tool’s (MSVC, SDKs) prompts.

You can add it to start menu or make a label (change script address at label preferences to «cmd /k path/to/setqtenv.cmd«).

What else can I do to speed up my build

Pure C++ techniques :

  • Use precompiled headers (PCH) : useful for big executables/libraries
  • Forward declare headers
  • Write less templates

QMake :

  • If you build in VisualStudio, install Qt Visual Studio Tools ≥ 2.2; which now supports parallel calls of moc.
  • If you use QMake and you have many projects to build, you can build them in parallel using a project without the directive.

Improve your build process :

  • Build CPP files and projects in parallel (ex qmake with subdirs, make -j8, vc++ /MP…)
  • Distribute your builds (ex distcc)
  • Install a compiler cache (ex ccache)
  • Build your project on linux instead of windows (big performance difference, even in a VM)

Tune your system :

  • On windows, whitelist your project directory in the antivirus
  • On windows, disable file indexation
  • Buy a RAMDisk, more CPU, etc.

Use better tools :

  • Zapcc is a fast alternative to Clang
  • Gold linker replaces ld (linux)
  • Replace Make with Ninja (best combo with CMake)
  • Add COTIRE to CMake to handle unity builds and precompiled headers
  • Install Incredybuild on Windows

The following links can also help you :

General advices :

Compile cache :

sccache, Mozilla’s distributed compiler cache, now written in Rust

Build instructions of big projects :

Configuration Features

qmake can be set up with extra configuration features that are specified in feature (.prf) files. These extra features often provide support for custom tools that are used during the build process. To add a feature to the build process, append the feature name (the stem of the feature filename) to the variable.

For example, qmake can configure the build process to take advantage of external libraries that are supported by pkg-config, such as the D-Bus and ogg libraries, with the following lines:

CONFIG += link_pkgconfig
PKGCONFIG += ogg dbus-1

For more information about adding features, see .

Описываем процедуру сборки в .travis.yml

Для начала нужно выбрать операционную систему, которая запускается как виртуальная машина на серверах Travis CI, и язык программирования.

language, насколько я понимаю, автоматизирует некоторые шаги если они не указаны явно, но его обязательность для меня загадка. Думал, что без него будет отсутствовать предустановленный MSVC, но во время экспериментов оказалось, что для других языков он тоже пристутствует.

Следующим шагом нужно скачать и установить необходимые зависимости. Для QtProtobuf, такими являются:

  • Qt 5.12.3 или выше
  • cmake-3.1 или выше
  • Strawberry perl 5.28 или выше
  • GoLang 1.10 или выше
  • Yasm 1.3 или выше
  • Visual Studio Compiler 14.16.x

Для начала скачиваем полный инсталлер Qt из официального репозитория:

Делаем установку необходимых зависимостей:

С установкой GoLang и Yasm думаю не должно быть вопросов. А вот запуску инсталлера Qt, я уделю больше внимания.

Здесь я отключаю все checkbox компоненты вызовом и включаю необходимый для постройки «qt.qt5.5132.win32_msvc2017». Тут имеются 2 аспекта, которые важны при написании этой процедуры:

  • selectComponent работает также как и графический компонент, а потому зависимости и подкомпоненты выбираются по той же логике, как если бы мы выбрали их в графическом интерфейсе. Именно поэтому не нужно переживать по-поводу разрешения зависимостей.
  • Названия компонент можно посмотреть в «вербальном» режиме установки. Для этого я в одну из итераций выполнил и запустил установку скомандой . В логах вы с легкостью можете найти все необходимые вам компоненты и модерировать их установку при помощи widget.selectComponent/widget.deselectComponent.

Так же в связи с изменениями в политике Qt, необходимо установить логин и пароль для пользователя

И последний важный момент, который я затрону в этом tutorial — это окружение для сборки. Из-за того, что установка зависимостей и сборка происходят в рамках одного shell, после уставновки Go и Yasm в нашем shell нет прописаного PATH до исполняемых файлов. Поэтому необходимо вручную прописать PATH, GOROOT перед простраением:

Еще хочется обратить внимание на то, что в CMAKE_PREFIX_PATH по аналогии необходимо прописать путь до Go и Yasm для корректной работы функции find_program. Возможно позже я соберусь описать создание docker-контейнера для сборки с Qt на борту

Возможно позже я соберусь описать создание docker-контейнера для сборки с Qt на борту.

Список переменных

Далее представлен список наиболее часто используемых переменных и описание их содержания.

  • CONFIG

    — Основные параметры настройки проекта

  • DESTDIR

    — Директория, в которую будет помещён бинарник или исполняемый файл

  • FORMS

    — Список UI файлов, которые реализуют пользовательский интерфейс

  • HEADERS

    — Список имён заголовочных файлов (.h) и путей к ним

  • QT

    — Список модулей Qt, используемых в проекте

  • RESOURCES

    — список ресурсный файлов (.qrc), включаемых в финальный проект.

  • SOURCES

    — список файлов исходных кодов, которые используются при сборке проекта.

  • TEMPLATE

    — шаблон, используемый в проекте. Определяет то, чем будет проект после компиляции, приложением, библиотекой или плагином.

Содержимое переменных может быть присвоено другим переменным с помощью подстановки двух знаков  $ перед именем других переменных.

Stopping qmake If a File Does Not Exist

You may not want to create a Makefile if a certain file does not exist. We can check if a file exists by using the function. We can stop qmake from processing by using the function. This works in the same way as scopes do. Simply replace the scope condition with the function. A check for a file called main.cpp looks like this:

!exists( main.cpp ) {
    error( "No main.cpp file found" )
}

The symbol is used to negate the test. That is, is true if the file exists, and is true if the file does not exist.

CONFIG += debug
HEADERS += hello.h
SOURCES += hello.cpp
SOURCES += main.cpp
win32 {
    SOURCES += hellowin.cpp
}
unix {
    SOURCES += hellounix.cpp
}
!exists( main.cpp ) {
    error( "No main.cpp file found" )
}

Use qmake as before to generate a makefile. If you rename temporarily, you will see the message and qmake will stop processing.

Что получилось

cmake_minimum_required (VERSION 2.6)
 
set (PROJECT 
	demo)
 
set (HEADERS 
	../main_window.h)
 
set (SOURCES 
	../main_window.cpp
	../main.cpp)
 
set (LIBRARIES
	library)
 
set (LANGUAGES
	rus
	eng)
 
set (RESOURCE_PATH 
	../resources)
 
set (RESOURCES 
	${RESOURCE_PATH}/resources.qrc)
 
set (TRANSLATIONS_PATH 
	../resources/translations)
 
project (${PROJECT})
 
include_directories (../)
 
find_package (Qt4 REQUIRED)
include (${QT_USE_FILE})
qt4_add_resources (QRC_SOURCES ${RESOURCES})
qt4_wrap_cpp (MOC_SOURCES ${HEADERS})
foreach (LANGUAGE ${LANGUAGES})
	set (TS ${TRANSLATIONS_PATH}/${LANGUAGE}.ts)
	set (QM ${TRANSLATIONS_PATH}/${LANGUAGE}.qm)
	set (TRANSLATIONS ${TRANSLATIONS} ${TS})
	set (TRANSLATIONS_BINARY ${TRANSLATIONS_BINARY} ${QM})
	add_custom_command (
		OUTPUT ${QM}
		COMMAND ${QT_LRELEASE_EXECUTABLE} ${TS}
		MAIN_DEPENDENCY ${TS})
endforeach()
add_custom_target (
	translations 
	COMMAND ${QT_LUPDATE_EXECUTABLE} ${HEADERS} ${SOURCES} -ts ${TRANSLATIONS})
add_custom_command (
	TARGET translations
	COMMAND ${QT_LRELEASE_EXECUTABLE} ${TRANSLATIONS})
 
foreach (LIBRARY ${LIBRARIES})
	add_subdirectory (../${LIBRARY}/build bin/${LIBRARY})
endforeach ()
 
if (MSVC)
	add_definitions (/W3)
elseif (CMAKE_COMPILER_IS_GNUCXX)
	add_definitions (-Wall -pedantic)
else ()
	message ("Unknown compiler")
endif ()
 
source_group ("Header Files" FILES ${HEADERS})
source_group ("Source Files" FILES ${SOURCES})
source_group ("Generated Files" FILES ${MOC_SOURCES})
source_group ("Resource Files" FILES ${QRC_SOURCES})
 
add_executable (${PROJECT} ${HEADERS} ${SOURCES} ${MOC_SOURCES} ${QRC_SOURCES} ${TRANSLATIONS})
 
target_link_libraries (${PROJECT} ${LIBRARIES} ${QT_LIBRARIES})

Конфигурирование и сборка

Установите путь так, чтобы использовать инструменты Qt5, а не старые Qt4 и прочие, которые могут присутствовать в системе:

Для Linux/Mac OS X:

unset QTDIR
export PATH="$PWD/qtbase/bin:$PWD/qtrepotools/bin:$PATH"

Для Windows:

set QTDIR=
set PATH=%CD%\qtbase\bin;%CD%\qtrepotools\bin;%PATH%

Теперь сконфигурируйте сборку (из директории верхнего уровня). Отключение тестов tests и примеров examples значительно ускорит компиляцию:

Для Linux/Mac OS X:

.configure -developer-build -opensource -nomake examples -nomake tests

Для Windows:

configure -developer-build -opensource -nomake examples -nomake tests
  • -developer-build — эта опция экспортирует больше символов, чем в традиционной сборке Qt, что позволяет большему количеству классов и функций быть протестированными модулем. Это также значение по умолчанию для сборки отладочной версии и установки двоичных файлов в текущем каталоге, и позволяет избежать потребности в ‘make install’.
  • -opensource — устанавливает лицензию LGPL 2.1.
  • -nomake examples и -nomake tests — исключение из сборки тестов и примеров. В дальнейшем вы всегда можете собрать их отдельно.

Подсказка 1: На Linux вы должны также передать параметр -no-gtkstyle. Это вызвано тем, что в ряде систем (по крайней мере, SUSE и Gentoo) pkg-config —cflags gtk+–2.0 фактически возвращает пути, которые включают в систему Qt4.x-include каталоги.

Подсказка 2: Можете добавить -confirm-license, чтобы принять лицензию и избавиться от вопроса о ее принятии.

Подсказка 3: На Windows вы не в состоянии осуществить сборку, если sh.exe находится в PATH (например, из-за установленного git или msys). Такая ошибка обозначается в сообщениях qt5-srcqtbasebinqmake.exe: command not found и подобных. В этом случае удостоверьтесь, что sh.exe не указан в переменной PATH. Вы должны будете вновь сконфигурировать сборку, в случае если вы его удалили.

Запускаем сборку, вызывая build perl сценарий:

Для Linux:

.build -j 3

Для Windows (MSVC):

perl build

Или просто соберите определенный модуль, например, declarative, и модули, от которых он зависит:

make module-qtdeclarative

Подсказка 1: build сценарий используется для сборки всей конфигурации. Для сборки модулей из каталогов с исходниками, вы можете выполнять команду make. Это тоже работает.
Подсказка 2: jom, низкоуровневая замена nmake на Windows, она пока не правильно работает для высокоуровневых сборок. Однако, вы можете использовать его для (пере-)создания отдельных подмодулей.

Сборка QtWebKit

Linux, Mac

Для сборки потребуются инструменты bison, flex и gperf.

cd qtwebkit
export WEBKITOUTPUTDIR="$PWD/WebKitBuild"
perl ToolsScriptsbuild-webkit --qt --qmake="$PWD/../qtbase/bin/qmake" --install-libs=<install dir> --debug 
     --makeargs="$MAKEFLAGS"

Windows

  • Добавить c:\phtreads\pthreads.2 в переменную окружения INCLUDE
  • Добавить c:\phtreads\Pre-built.2\lib\x64 или c:\phtreads\Pre-built.2\lib\x86 в переменную окружения LIB
  • Добавить c:\phtreads\Pre-built.2\dll\x64 или c:\phtreads\Pre-built.2\dllx86 в переменную окружения PATH

Инструменты bison, flex и gperf, которые требуются для сборки, предусмотрительно размещены в папке gnuwin32\bin.

set PATH=%PATH%;%CD%\gnuwin32\bin
cd qtwebkit
set WEBKITOUTPUTDIR=%CD%\WebKitBuild
perl Tools\Scripts\build-webkit --qt --qmake="%CD%\\..\\qtbase\\bin\\qmake.exe" --install-libs=<install dir> 
     --release --makeargs="%MAKEFLAGS%"

Code restrictions

  • With unity builds, can trigger errors when building multiple CPP files together.
    The most recurrent error is symbol name conflicts among unrelated namespaces.
    That is why, by default, a class that contains will not be grouped by qmake-unity (slower, but safe build).
    However, you might want to whitelist a few safe namespaces (especially your owns) to get a faster build.
    This is right as long as the class/function/static variables names remain unique.
    To whitelist namespaces, please edit the variable in unity_config.py.

  • and are not supported.
    You should add the comment on top of these files.

  • should be used instead of include guards to enable optimization.
    If is enabled and is not found in a header, it will not be grouped by qmake-unity (slower, but safe build)

  • PIMPL modules are not supported.
    However, if your PIMPL modules does not have the directive at the end of the CPP file, you might try to disable this restriction.

General concepts

Unity build, jumbo builds and single compilation unit (SCU) are a technique to speed up C++ compilation process.
It consists of grouping/merging several CPP files before compilation.
QMake-unity automates the process of grouping files and may speed up the compilation by .

It can act at two levels :

  • group CPP files before CL is called
  • group header files before MOC is called

There are two optimization levels for moc objects :

  • call MOC on every QObject classes (headers), then group the cpp files generated by moc to build them in a single pass with CL. ()
  • group every QObject classes (headers) into a single header, then call moc on this file. (, even faster)

QMake-unity provides good integration with Qt 5 tooling system (qmake, moc, qt-creator) and with MSBuild.
It is compatible with precompiled headers (PCH).

Here are general articles if you want to understand how it works :

Starting Off Simple

Let’s assume that you have just finished a basic implementation of your application, and you have created the following files:

  • hello.cpp
  • hello.h
  • main.cpp

You will find these files in the directory of the Qt distribution. The only other thing you know about the setup of the application is that it’s written in Qt. First, using your favorite plain text editor, create a file called in . The first thing you need to do is add the lines that tell qmake about the source and header files that are part of your development project.

We’ll add the source files to the project file first. To do this you need to use the variable. Just start a new line with and put hello.cpp after it. You should have something like this:

SOURCES += hello.cpp

We repeat this for each source file in the project, until we end up with the following:

SOURCES += hello.cpp
SOURCES += main.cpp

If you prefer to use a Make-like syntax, with all the files listed in one go you can use the newline escaping like this:

SOURCES = hello.cpp \
          main.cpp

Now that the source files are listed in the project file, the header files must be added. These are added in exactly the same way as source files, except that the variable name we use is .

Once you have done this, your project file should look something like this:

HEADERS += hello.h
SOURCES += hello.cpp
SOURCES += main.cpp

The target name is set automatically. It is the same as the project filename, but with the suffix appropriate for the platform. For example, if the project file is called , the target will be on Windows and on Unix. If you want to use a different name you can set it in the project file:

TARGET = helloworld

The finished project file should look like this:

HEADERS += hello.h
SOURCES += hello.cpp
SOURCES += main.cpp

You can now use qmake to generate a Makefile for your application. On the command line, in your project directory, type the following:

qmake -o Makefile hello.pro

Then type or depending on the compiler you use.

For Visual Studio users, qmake can also generate Visual Studio project files. For example:

qmake -tp vc hello.pro

Adding Platform-Specific Source Files

After a few hours of coding, you might have made a start on the platform-specific part of your application, and decided to keep the platform-dependent code separate. So you now have two new files to include into your project file: and . We cannot just add these to the variable since that would place both files in the Makefile. So, what we need to do here is to use a scope which will be processed depending on which platform we are building for.

A simple scope that adds the platform-dependent file for Windows looks like this:

win32 {
    SOURCES += hellowin.cpp
}

When building for Windows, qmake adds to the list of source files. When building for any other platform, qmake simply ignores it. Now all that is left to be done is to create a scope for the Unix-specific file.

When you have done that, your project file should look something like this:

CONFIG += debug
HEADERS += hello.h
SOURCES += hello.cpp
SOURCES += main.cpp
win32 {
    SOURCES += hellowin.cpp
}
unix {
    SOURCES += hellounix.cpp
}

Use qmake as before to generate a Makefile.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector