Linux qt creator статистическая линковка

Due to the proliferation of Unix systems (commercial Unices, Linux distributions, etc.), deployment on Unix is a complex topic. Before we start, be aware that programs compiled for one Unix flavor will probably not run on a different Unix system. For example, unless you use a cross-compiler, you cannot compile your application on Irix and distribute it on AIX.

Этот документ описывает, как определить, какие файлы вы должны включить в ваш дистрибутив, и как убедиться, что приложение найдет их во время выполнения. Мы продемонстрируем процедуры на примере развертывания приложения Plug & Paint, которое находится в каталоге примеров Qt.

Статическая линковка

Static linking is often the safest and easiest way to distribute an application on Unix since it relieves you from the task of distributing the Qt libraries and ensuring that they are located in the default search path for libraries on the target system.

Статическая сборка Qt

To use this approach, you must start by installing a static version of the Qt library:

We specify the prefix so that we do not overwrite the existing Qt installation. The example above only builds the Qt libraries, i.e. the examples and Qt Designer will not be built. When make is done, you will find the Qt libraries in the /path/to/Qt/lib directory.

When linking your application against static Qt libraries, note that you might need to add more libraries to the LIBS line in your project file. Для получения дополнительной информации, смотрите раздел Зависимости приложения.

Линковка приложения со статической версией Qt

Once Qt is built statically, the next step is to regenerate the makefile and rebuild the application. Сначала мы должны перейти в каталог, который содержит приложение:

Now run qmake to create a new makefile for the application, and do a clean build to create the statically linked executable:

Вы, вероятно, хотите линковать библиотеки в release режиме, и вы можете указать это при вызове qmake. Note that we must set the path to the static Qt that we just built.

To check that the application really links statically with Qt, run the ldd tool (available on most Unices):

Verify that the Qt libraries are not mentioned in the output.

Now, provided that everything compiled and linked without any errors, we should have a plugandpaint file that is ready for deployment. Один простой способ проверить, что приложение действительно может быть запущено автономно — это скопировать его на машину, которая или не имеет Qt или не имеет установленных приложений Qt, и запустить его на этой машине.

Помните, что если ваше приложение зависит от библиотек компилятора, они должны распространяться вместе с вашим приложением. For more information, see the Application Dependencies section.

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 executable we have prepared so far is incomplete. The application will run, but the functionality will be disabled due to the missing plugins. Для развертывания приложения на основе подключаемых модулей мы должны использовать подход с разделяемыми библиотеками.

Разделяемые библиотеки

У нас есть ещё две проблемы при развёртывании приложения Plug & Paint с использованием разделяемых библиотек: среда Qt должна быть правильно настроена для исполнения приложения, а также подключаемые модули должны быть установлены в правильную директорию в системе, чтобы приложение могло их найти.

Читайте также:  Где хранится backup windows

Сборка Qt как разделяемой библиотеки

We assume that you already have installed Qt as a shared library, which is the default when installing Qt, in the /path/to/Qt directory. Для получения более подробной информации о том, как собрать Qt, смотрите документацию по Установке.

Линковка приложения с Qt как разделяемой библиотекой

После того, как мы убедились, что Qt собрана как разделяемая библиотека, мы можем собрать приложение Plug & Paint. Сначала мы должны перейти в каталог, который содержит приложение:

Now run qmake to create a new makefile for the application, and do a clean build to create the dynamically linked executable:

Этим основное приложение будет собрано, далее собираем подключаемые модули:

If everything compiled and linked without any errors, we will get a plugandpaint executable and the libpnp_basictools.so and libpnp_extrafilters.so plugin files.

Создание пакета приложения

There is no standard package management on Unix, so the method we present below is a generic solution. See the documentation for your target system for information on how to create a package.

To deploy the application, we must make sure that we copy the relevant Qt libraries (corresponding to the Qt modules used in the application) as well as the executable to the same directory. Remember that if your application depends on compiler specific libraries, these must also be redistributed along with your application. For more information, see the Application Dependencies section.

We’ll cover the plugins shortly, but the main issue with shared libraries is that you must ensure that the dynamic linker will find the Qt libraries. Unless told otherwise, the dynamic linker doesn’t search the directory where your application resides. There are many ways to solve this:

  • You can install the Qt libraries in one of the system library paths (e.g. /usr/lib on most systems).
  • You can pass a predetermined path to the -rpath command-line option when linking the application. This will tell the dynamic linker to look in this directory when starting your application.
  • You can write a startup script for your application, where you modify the dynamic linker configuration (e.g. adding your application’s directory to the LD_LIBRARY_PATH environment variable).

The disadvantage of the first approach is that the user must have super user privileges. The disadvantage of the second approach is that the user may not have privileges to install into the predetemined path. In either case, the users don’t have the option of installing to their home directory. We recommend using the third approach since it is the most flexible. For example, a plugandpaint.sh script will look like this:

By running this script instead of the executable, you are sure that the Qt libraries will be found by the dynamic linker. Note that you only have to rename the script to use it with other applications.

When looking for plugins, the application searches in a plugins subdirectory inside the directory of the application executable. Either you have to manually copy the plugins into the plugins directory, or you can set the DESTDIR in the plugins’ project files:

An archive distributing all the Qt libraries, and all the plugins, required to run the Plug & Paint application, would have to include the following files:

Компонент Имя файла
Исполняемый файл plugandpaint
The script to run the executable plugandpaint.sh
Подключаемый модуль основных инструментов plugins\libpnp_basictools.so
Подключаемый модуль ExtraFilters plugins\libpnp_extrafilters.so
Модуль Qt Core libQtCore.so.4
Модуль Qt GUI libQtGui.so.4

On most systems, the extension for shared libraries is .so. A notable exception is HP-UX, which uses .sl.

Помните, что если ваше приложение зависит от библиотек компилятора, они должны распространяться вместе с вашим приложением. For more information, see the Application Dependencies section.

To verify that the application now can be successfully deployed, you can extract this archive on a machine without Qt and without any compiler installed, and try to run it, i.e. run the plugandpaint.sh script.

An alternative to putting the plugins in the plugins subdirectory is to add a custom search path when you start your application using QApplication::addLibraryPath() or QApplication::setLibraryPaths().

Зависимости приложения

Дополнительные библиотеки

To find out which libraries your application depends on, run the ldd tool (available on most Unices):

This will list all the shared library dependencies for your application. Depending on configuration, these libraries must be redistributed along with your application. In particular, the standard C++ library must be redistributed if you’re compiling your application with a compiler that is binary incompatible with the system compiler. When possible, the safest solution is to link against these libraries statically.

You will probably want to link dynamically with the regular X11 libraries, since some implementations will try to open other shared libraries with dlopen(), and if this fails, the X11 library might cause your application to crash.

It’s also worth mentioning that Qt will look for certain X11 extensions, such as Xinerama and Xrandr, and possibly pull them in, including all the libraries that they link against. If you can’t guarantee the presence of a certain extension, the safest approach is to disable it when configuring Qt (e.g. ./configure -no-xrandr).

FontConfig and FreeType are other examples of libraries that aren’t always available or that aren’t always binary compatible. As strange as it may sound, some software vendors have had success by compiling their software on very old machines and have been very careful not to upgrade any of the software running on them.

When linking your application against the static Qt libraries, you must explicitly link with the dependent libraries mentioned above. Do this by adding them to the LIBS variable in your project file.

Подключаемые модули Qt

Ваше приложение может также зависить от одного или более подключаемых модулей Qt, таких как подключаемый модуль формата изображения JPEG или подключаемый модуль драйвера SQL. Be sure to distribute any Qt plugins that you need with your application.

Путь поиска для подключаемых модулей Qt (так же как несколько других путей) жестко запрограммировано в библиотеке QtCore. По умолчанию, первым путем поиска подключаемого модуля будет жестко запрограммирован как /path/to/Qt/plugins. As mentioned above, using pre-determined paths has certain disadvantages, so you need to examine various alternatives to make sure that the Qt plugins are found:

Источник

Статическая линковка

Здравствуйте! Последние несколько дней пытаюсь собрать Qt для стат. сборки, безуспешно. Не даст-ли какой-нибудь добрый человек мне архивчик с собранной и настроенной Qt?

Знаю что подобные вопросы задавались здесь уже кучу раз, знаю что вопрос отдает наглостью, но все же.

Qt 5.1.1 статическая линковка
Да, наверное такая тема часто проскальзывает, но я все равно не понял. (( Я начал изучать Qt и.

Статическая линковка Qt
Есть несколько вопросов. 1) Порядка скольки времени могут собираться исходники Qt? Не обязательно.

Статическая линковка в Qt 5.11
Собственно, сабж. Актуальна ли информация из важной темы.

Статическая линковка Qt 5.6
Решил я обновить Qt до 5.6. После чего надо было собрать комплект статической сборки. Решил.

Вы бы хоть ОС и разрядность написали.
Да и статическая сборка — вещь хитрая. Вы должны будете затем найти и использовать то же окружение (компилятор и тд.) что и у автора сборки.
Так что если вам прямо горит собрать стат. сборку — то пишите какие у вас были ошибки.

недавно делал, в теме есть видео + расписано по шагам, куда чего нажимать, сборка была под windows 7 x64, QTCreator 5.2, mingw 4.8 все работает. exe собирался около 1.5 часов.

MAKAPOH, а там правильная ссылка? Я с неё скачал только msys2-i686-20141113.exe весом 48 МБайт

Помощь в написании контрольных, курсовых и дипломных работ здесь.

Статическая линковка QTSDK
вообщем делал всё как в 3 посте этой темы в итоге получил следующие ошибки. что не так ?

QtSDK 4.8 статическая линковка
Всем привет, в винде совсем ничего не понимаю, так как всё жизнь на линухе сижу Хочу собирать.

Статическая линковка — ошибка компиляции
Собрал статическую Qt 5.2.0 (по этой инструкции с указанием -debug-and-release). Сборка прошла без.

Статическая линковка QT Creator Linux
Доброго времени суток, простите за этот вопрос, но это единственный выход теперь. Начитался гугла.

Источник

Статическая линковка QT Creator Linux

При запуске на пк без QT естественно ошибки libQT5Core.so no version information available и тд

Добавлено через 9 минут
Версия QT Creator 5.10.1

Добавлено через 37 минут
Проблема с «You don’t seem to have ‘make’ or ‘gmake’ in your PATH». была связана с тем , что архив распаковал не с помощью tar -xzvf qt-everywhere-opensource-src-5.2.0.tar.gz

Добавлено через 37 минут
Можно не линковать статически, а просто подсунуть необходимые библиотеки в папку с программой? Потому что линкованная статически, стала бажить до ужаса((

Статическая линковка в Qt 5.11
Собственно, сабж. Актуальна ли информация из важной темы.

Статическая линковка Qt
Есть несколько вопросов. 1) Порядка скольки времени могут собираться исходники Qt? Не обязательно.

Статическая линковка Qt 5.6
Решил я обновить Qt до 5.6. После чего надо было собрать комплект статической сборки. Решил.

Qt 5.1.1 статическая линковка
Да, наверное такая тема часто проскальзывает, но я все равно не понял. (( Я начал изучать Qt и.

интегрированную среду разработки программного обеспечения. К чему именно, а главное, зачем он собрался ее «линковать» — сие тайна есть, мраком глубоким покрытая.

Это вообще шедевр, поисковиками мы с вами явно разными пользуемся.

Похоже, что для вас вообще нет разницы между SDK и IDE.

TRam_, а подскажите как это сделать, пожалуйста.

Добавлено через 1 минуту
0x90h, до трех ночи) (не в три)

Добавлено через 2 минуты
0x90h, sdk пакет разработчика, ide — среда разработки. Я понимаю, что вам это выглядит абсурдно и смешно. Но если это легко сделать, может вы подскажите?

Добавлено через 37 минут
ошибки libQT5Core.so iiQTGui5.so no version information available. — на другой машине.

Добавлено через 5 часов 49 минут
Может можно собрать Deb пакет со всеми зависимостями?.

Никто адекватного ответа дать не смог. Теперь по традиции, то что я дальше напишу обсмеют. Но для таких же как и я, если наткнетесь на эту тему- надеюсь для вас будет полезно!

Если вы делали проект на Linux’e в QT не собирая его в статику, то Вам надо перейти по ссылке https://download.qt.io/archive/qt/ , выбрать версию установленную на вашем ПК (с версиями ниже могут быть проблемы), найти файл вида qt-everywhere-src-5.10.1.tar.xz , обычно лежит в папке Single. После того как скачали файл, необходимо его разархивировать и выполнить bash скрипт.

После в созданной папке /path/to/Q/Qt5_static \ в подпапке bin будет лежать файл QMAKE, к которому надо указать путь в самой QT (Инструменты-Параметры-Профили QT-Добавить — и выбираем файл qmake из папки /path/to/Q/Qt5_static/bin

Жмем применить — переходим на вкладку комплекты — жмем добавить, внизу в списке находим профиль QT и выбираем созданный на предыдущем шаге профиль. Жмем применить и ок. Выходим из настроек. Жмем CTRL +5 и добавляем к проекту новый вариант сборки. — Более подробно об этом по ссылке ниже.

Источник

Читайте также:  Как запустить код с linux
Оцените статью