Оглавление
Развёртывание приложения в Mac OS XНачиная с Qt 4.5 в комплект поставки включён инструмент портирования, который автоматизирует процедуры, описанные здесь. Этот документ описывает, как создать пакет и как убедиться, что приложение найдёт нужные ему ресурсы во время выполнения. Мы продемонстрируем процедуры на примере развертывания приложения Plug & Paint, которое находится в каталоге примеров Qt. ПакетВ Mac приложение с ГПИ должно быть собрано и запущено из пакета. Пакетом является структура каталогов, которая при просмотре в Finder-е выглядит как единое целое. Пакет приложения обычно содержит исполняемый файл и все необходимые ресурсы. Смотрите изображение ниже: Пакет предоставляет пользователю многие преимущества. One primary advantage is that, since it is a single entity, it allows for drag-and-drop installation. As a programmer you can access bundle information in your own code. This is specific to Mac OS X and beyond the scope of this document. More information about bundles is available on Apple's Developer Website. A Qt command line application on Mac OS X works similar to a command line application on Unix and Windows. You probably don't want to run it in a bundle: Add this to your application's .pro: CONFIG-=app_bundle This will tell qmake not to put the executable inside a bundle. Please refer to the X11 deployment documentation for information about how to deploy these "bundle-less" applications. XcodeWe will only concern ourselves with command-line tools here. While it is possible to use Xcode for this, Xcode has changed enough between each version that it makes it difficult to document it perfectly for each version. A future version of this document may include more information for using Xcode in the deployment process. Статическая линковкаIf you want to keep things simple by only having a few files to deploy, then you must build everything statically. Статическая сборка QtStart by installing a static version of the Qt library. Remember that you will not be able to use plugins and you must build in all the image formats, SQL drivers, etc.. cd /path/to/Qt ./configure -static <other parameters> make sub-src You can check the various options that are available by running configure -help. Линковка приложения со статической версией QtOnce Qt is built statically, the next step is to regenerate the makefile and rebuild the application. Сначала мы должны перейти в каталог, который содержит приложение: cd /path/to/Qt/examples/tools/plugandpaint Now run qmake to create a new makefile for the application, and do a clean build to create the statically linked executable: make clean qmake -config release make Вы, вероятно, хотите линковать библиотеки в release режиме, и вы можете указать это при вызове qmake. If you have Xcode Tools 1.5 or higher installed, you may want to take advantage of "dead code stripping" to reduce the size of your binary even more. You can do this by passing LIBS+= -dead_strip to qmake in addition to the -config release parameter. This doesn't have as large an effect if you are using GCC 4, since Qt will then have function visibility hints built-in, but if you use GCC 3.3, it could make a difference. Now, provided that everything compiled and linked without any errors, we should have a plugandpaint.app bundle that is ready for deployment. One easy way to check that the application really can be run stand-alone is to copy the bundle to a machine that doesn't have Qt or any Qt applications installed, and run the application on that machine. You can check what other libraries your application links to using the otool: otool -L plugandpaint.app/Contents/MacOs/plugandpaint Here is what the output looks like for the static Plug & Paint: plugandpaint.app/Contents/MacOS/plugandpaint: /System/Library/Frameworks/Carbon.framework/Versions/A/Carbon (compatibility version 2.0.0, current version 128.0.0) /System/Library/Frameworks/QuickTime.framework/Versions/A/QuickTime (compatibility version 1.0.0, current version 10.0.0) /usr/lib/libz.1.dylib (compatibility version 1.0.0, current version 1.2.3) /System/Library/Frameworks/ApplicationServices.framework/Versions/A/ApplicationServices (compatibility version 1.0.0, current version 22.0.0) /usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.3.0) /usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0) /usr/lib/libmx.A.dylib (compatibility version 1.0.0, current version 92.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 88.0.0) For more information, see the Application Dependencies section. If you see Qt libraries in the output, it probably means that you have both dynamic and static Qt libraries installed on your machine. The linker will always choose dynamic over static. There are two solutions: Either move your Qt dynamic libraries (.dylibs) away to another directory while you link the application and then move them back, or edit the Makefile and replace link lines for the Qt libraries with the absolute path to the static libraries. Например, замените -lQtGui на /where/static/qt/lib/is/libQtGui.a The Plug & Paint example consists of several components: The core application (Plug & Paint), and the Basic Tools and Extra Filters plugins. Since we cannot deploy plugins using the static linking approach, the bundle we have prepared so far is incomplete. The application will run, but the functionality will be disabled due to the missing plugins. To deploy plugin-based applications we should use the framework approach. ФреймворкиWe have two challenges when deploying the Plug & Paint application using frameworks: The Qt runtime has to be correctly redistributed along with the application bundle, and the plugins have to be installed in the correct location so that the application can find them. When distributing Qt with your application using frameworks, you have two options: You can either distribute Qt as a private framework within your application bundle, or you can distribute Qt as a standard framework (alternatively use the Qt frameworks in the installed binary). These two approaches are essentially the same. The latter option is good if you have many Qt applications and you would prefer to save memory. The former is good if you have Qt built in a special way, or want to make sure the framework is there. It just comes down to where you place the Qt frameworks. Сборка Qt в виде фреймворкаWe assume that you already have installed Qt as frameworks, which is the default when installing Qt, in the /path/to/Qt directory. For more information on how to build Qt, see the Installation documentation. When installing, the identification name of the frameworks will also be set. The identification name is what the dynamic linker (dyld) uses to find the libraries for your application. Линковка приложения с Qt как фреймворкаAfter ensuring that Qt is built as frameworks, we can build the Plug & Paint application. Сначала мы должны перейти в каталог, который содержит приложение: cd /path/to/Qt/examples/tools/plugandpaint Now run qmake to create a new makefile for the application, and do a clean build to create the dynamically linked executable: make clean qmake -config release make Этим основное приложение будет собрано, далее собираем подключаемые модули: cd ../plugandpaintplugins make clean qmake -config release make Now run the otool for the Qt frameworks, for example Qt Gui: otool -L QtGui.framework/QtGui Вы получите следующий вывод: QtGui.framework/QtGui: /path/to/Qt/lib/QtGui.framework/Versions/4.0/QtGui (compatibility version 4.0.0, current version 4.0.1) /System/Library/Frameworks/Carbon.framework/Versions/A/Carbon (compatibility version 2.0.0, current version 128.0.0) /System/Library/Frameworks/QuickTime.framework/Versions/A/QuickTime (compatibility version 1.0.0, current version 10.0.0) /path/to/Qt/QtCore.framework/Versions/4.0/QtCore (compatibility version 4.0.0, current version 4.0.1) /usr/lib/libz.1.dylib (compatibility version 1.0.0, current version 1.2.3) /System/Library/Frameworks/ApplicationServices.framework/Versions/A/ApplicationServices (compatibility version 1.0.0, current version 22.0.0) /usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.3.0) /usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0) /usr/lib/libmx.A.dylib (compatibility version 1.0.0, current version 92.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 88.0.0) For the Qt frameworks, the first line (i.e. path/to/Qt/lib/QtGui.framework/Versions/4/QtGui (compatibility version 4.0.0, current version 4.0.1)) becomes the framework's identification name which is used by the dynamic linker (dyld). But when you are deploying the application, your users may not have the Qt frameworks installed in the specified location. For that reason, you must either provide the frameworks in an agreed upon location, or store the frameworks in the bundle itself. Regardless of which solution you choose, you must make sure that the frameworks return the proper identification name for themselves, and that the application will look for these names. Luckily we can control this with the install_name_tool command-line tool. The install_name_tool works in two modes, -id and -change. The -id mode is for libraries and frameworks, and allows us to specify a new identification name. We use the -change mode to change the paths in the application. Let's test this out by copying the Qt frameworks into the Plug & Paint bundle. Looking at otool's output for the bundle, we can see that we must copy both the QtCore and QtGui frameworks into the bundle. We will assume that we are in the directory where we built the bundle. mkdir plugandpaint.app/Contents/Frameworks cp -R /path/to/Qt/lib/QtCore.framework plugandpaint.app/Contents/Frameworks cp -R /path/to/Qt/lib/QtGui.framework plugandpaint.app/Contents/Frameworks First we create a Frameworks directory inside the bundle. This follows the Mac OS X application convention. We then copy the frameworks into the new directory. Since frameworks contain symbolic links, and we want to preserve them, we use the -R option. install_name_tool -id @executable_path/../Frameworks/QtCore.framework/Versions/4.0/QtCore plugandpaint.app/Contents/Frameworks/QtCore.framework/Versions/4.0/QtCore install_name_tool -id @executable_path/../Frameworks/QtGui.framework/Versions/4.0/QtGui plugandpaint.app/Contents/Frameworks/QtGui.framework/Versions/4.0/QtGui Then we run install_name_tool to set the identification names for the frameworks. The first argument after -id is the new name, and the second argument is the framework which identification we wish to change. The text @executable_path is a special dyld variable telling dyld to start looking where the executable is located. The new names specifies that these frameworks will be located "one directory up and over" in the Frameworks directory. install_name_tool -change path/to/Qt/lib/QtCore.framework/Versions/4.0/QtCore @executable_path/../Frameworks/QtCore.framework/Versions/4.0/QtCore plugandpaint.app/Contents/MacOs/plugandpaint install_name_tool -change path/to/qt/lib/QtGui.framework/Versions/4.0/QtGui @executable_path/../Frameworks/QtGui.framework/Versions/4.0/QtGui plugandpaint.app/Contents/MacOs/plugandpaint Now, the dynamic linker knows where to look for QtCore and QtGui. Then we must make the application aware of the library locations as well using install_name_tool's -change mode. This basically comes down to string replacement, to match the identification names that we set for the frameworks. Finally, since the QtGui framework depends on QtCore, we must remember to change the reference for QtGui: install_name_tool -change path/to/Qt/lib/QtCore.framework/Versions/4.0/QtCore @executable_path/../Frameworks/QtCore.framework/Versions/4.0/QtCore plugandpaint.app/Contents/Frameworks/QtGui.framework/Versions/4.0/QtGui After all this we can run otool again and see that the application will look in the right locations. Of course, the thing that makes the Plug & Paint example interesting are its plugins. The basic steps we need to follow with plugins are:
While we can put the plugins anywhere we want in the bundle, the best location to put them is under Contents/Plugins. When we built the Plug & Paint plugins, the DESTDIR variable in their .pro file put the plugins' .dylib files in a plugins subdirectory in the plugandpaint directory. So, in this example, all we need to do is move this directory: mv plugins plugandpaint.app/Contents If we run otool on for example the Basic Tools plugin's .dylib file we get the following information. libpnp_basictools.dylib: libpnp_basictools.dylib (compatibility version 0.0.0, current version 0.0.0) /path/to/Qt/lib/QtGui.framework/Versions/4.0/QtGui (compatibility version 4.0.0, current version 4.0.1) /System/Library/Frameworks/Carbon.framework/Versions/A/Carbon (compatibility version 2.0.0, current version 128.0.0) /System/Library/Frameworks/QuickTime.framework/Versions/A/QuickTime (compatibility version 1.0.0, current version 10.0.0) /path/to/Qt/lib/QtCore.framework/Versions/4.0/QtCore (compatibility version 4.0.0, current version 4.0.1) /usr/lib/libz.1.dylib (compatibility version 1.0.0, current version 1.2.3) /System/Library/Frameworks/ApplicationServices.framework/Versions/A/ApplicationServices (compatibility version 1.0.0, current version 22.0.0) /usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.3.0) /usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0) /usr/lib/libmx.A.dylib (compatibility version 1.0.0, current version 92.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 88.0.0) Then we can see that the plugin links to the Qt frameworks it was built against. Since we want the plugins to use the framework in the application bundle we change them the same way as we did for the application. For example for the Basic Tools plugin: install_name_tool -change /path/to/Qt/lib/QtCore.framework/Versions/4.0/QtCore @executable_path/../Frameworks/QtCore.framework/Versions/4.0/QtCore plugandpaint.app/Contents/plugins/libpnp_basictools.dylib install_name_tool -change /path/to/Qt/lib/QtGui.framework/Versions/4.0/QtGui @executable_path/../Frameworks/QtGui.framework/Versions/4.0/QtGui plugandpaint.app/Contents/plugins/libpnp_basictools.dylib We must also modify the code in tools/plugandpaint/mainwindow.cpp to cdUp() one directory since the plugins live in the bundle. Add the following code to the mainwindow.cpp file: #elif defined(Q_OS_MAC) if (pluginsDir.dirName() == "MacOS") { pluginsDir.cdUp(); } #endif
Warning: When deploying plugins, and thus make changes to the source code, the default identification names are reset when rebuilding the application, and you must repeat the process of making your application link to the Qt frameworks in the bundle using install_name_tool. Now you should be able to move the application to another Mac OS X machine and run it without Qt installed. Alternatively, you can move your frameworks that live outside of the bundle to another directory and see if the application still runs. If you store the frameworks in another location than in the bundle, the technique of linking your application is similar; you must make sure that the application and the frameworks agree where to be looking for the Qt libraries as well as the plugins. Создание пакета приложенияWhen you are done linking your application to Qt, either statically or as frameworks, the application is ready to be distributed. Apple provides a fair bit of information about how to do this and instead of repeating it here, we recommend that you consult their software delivery documentation. Although the process of deploying an application do have some pitfalls, once you know the various issues you can easily create packages that all your Mac OS X users will enjoy. Зависимости приложенияПодключаемые модули QtВаше приложение может также зависеть от одного или более подключаемых модулей Qt, таких как подключаемый модуль формата изображения JPEG или подключаемый модуль драйвера SQL. Убедитесь, что вы распространяете все необходимые вашему приложению подключаемые модули Qt, и обратите внимание на то, что каждый тип подключаемого модуля должен находиться внутри специального подкаталога (таких как imageformats или sqldrivers) в вашем каталоге, как описано ниже. Замечание: Если вы развёртываете приложение, которое использует QtWebKit, чтобы отображать HTML-страницы из интернета, то вы должны включить все подключаемые модули текстовых кодеков, чтобы поддержать настолько много HTML-кодировок насколько это возможно. Путь поиска для подключаемых модулей Qt (так же как несколько других путей) жестко запрограммировано в библиотеке QtCore. По умолчанию, первым путем поиска подключаемого модуля будет жестко запрограммирован как /path/to/Qt/plugins. But using pre-determined paths has certain disadvantages. Например, они могут не существовать на целевой машине. По этой причине вам нужно изучить различные альтернативы, чтобы обеспечить нахождение подключаемых модулей Qt:
Документ Как создавать плагины Qt очертит вопросы, которым вам нужно уделить внимание при разработке и распространении подключаемых модулей для приложений Qt. Дополнительные библиотекиYou can check which libraries your application is linking against by using the otool tool. To use otool, all you need to do is to run it like this: otool -L MyApp.app/Contents/MacOS/MyApp Unlike the deployment processes on X11 and Windows, compiler specific libraries rarely have to be redistributed along with your application. But since Qt can be configured, built, and installed in several ways on Mac OS X, there are also several ways to deploy applications. Typically your goals help determine how you are going to deploy the application. The last sections describe a couple of things to keep in mind when you are deploying your application. Зависимости от версии Mac OS XFrom Qt 4.6, Mac OS X 10.3 (Panther) is no longer supported. Qt 4.6 applications can be built and deployed on Mac OS X 10.4 (Tiger) and higher. This is achieved using weak linking. In weak linking, Qt tests whether a function added in a newer version of Mac OS X is available on the computer it is running on. This allows Qt to use newer features, when it runs on a newer version of OS X, while remaining compatible on the older versions. For more information about cross development issues on Mac OS X, see Apple's Developer Website. Since the linker is set to be compatible with all OS X versions, you must change the MACOSX_DEPLOYMENT_TARGET environment variable to get weak linking to work for your application. Можно добавить: QMAKE_MACOSX_DEPLOYMENT_TARGET = 10.3 to your .pro file, and qmake will take care of this for you. For more information about C++ runtime environment, see Apple's Developer Website Развёртывание приложений Phonon в Mac OS X
Зависимости от архитектурыThe Qt for Mac OS X libraries, tools, and examples can be built "universal" (i.e. they run natively on both Intel and PowerPC machines). This is accomplished by passing -universal on the configure line of the source package, and requires that you use GCC 4.0.x. On PowerPC hardware you will need to pass the universal SDK as a command line argument to the Qt configure command. Например: ./configure (other arguments) -universal -sdk /Developer/SDKs/MacOSX10.4u.sdk From 4.1.1 the Qt binary package is already universal. If you want to create a binary that runs on older versions of PowerPC and x86, it is possible to build Qt for the PowerPC using GCC 3.3, and for x86 one using GCC 4.0, and use Apple's lipo(1) tool to stitch them together. This is beyond the scope of this document and is not something we have tried, but Apple documents it on their developer website. Once you have a universal Qt, qmake will generate makefiles that will build for its host architecture by default. If you want to build for a specific architecture, you can control this with the CONFIG line in your .pro file. Используйте CONFIG+=ppc для PowerPC, и CONFIG+=x86 для x86. If you desire both, simply add both to the CONFIG line. PowerPC users also need an SDK. Например: QMAKE_MAC_SDK=/Developer/SDKs/MacOSX10.4u.sdk CONFIG+=x86 ppc Besides lipo, you can also check your binaries with the file(1) command line tool or the Finder. Инструмент портирования MacThe Mac deployment tool can be found in QTDIR/bin/macdeployqt. It is designed to automate the process of creating a deployable application bundle that contains the Qt libraries as private frameworks. The mac deployment tool also deploys the Qt plugins, according to the following rules:
Note: If you want a 3rd party library to be included in your application bundle, then you must copy the library into the bundle manually, after the bundle is created. macdeployqt supports the following options:
|
Попытка перевода Qt документации. Если есть желание присоединиться, или если есть замечания или пожелания, то заходите на форум: Перевод Qt документации на русский язык... Люди внесшие вклад в перевод: Команда переводчиков |