Pkg config install linux

Pkg config install linux

Библиотека сайта rus-linux.net

На главную -> MyLDP -> Электронные книги по ОС Linux

Beyond Linux From Scratch. Version 2011-12-30
Назад 12. Программирование Вперед

Пакет pkg-config-0.26

Знакомимся с пакетом pkg-config

В пакете pkg-config находится инструментарий, предназначенный для передачи пути include и/или путей к библиотекам в скрипты сборки пакета, работающие во время выполнения команд configure и make.

Известно, что пакет правильно собирается и работает на платформе LFS-7.0.

Информация о пакете

  • Загрузка (HTTP): http://pkgconfig.freedesktop.org/releases/pkg-config-0.26.tar.gz
  • Загрузка (FTP): ftp://mirror.ovh.net/gentoo-distfiles/distfiles/pkg-config-0.26.tar.gz
  • Контрольная сумма MD5: 47525c26a9ba7ba14bf85e01509a7234
  • Размер загружаемого пакета: 392 KB
  • Оценочный размер требуемого дискового пространства: 3 MB
  • Оценочное время сборки: менее 0,1 SBU

Зависимости пакета pkg-config

Обязательные

Установка пакета pkg-config

Исправьте проблемы, возникающие в одном из тестов пакета pkg-config:

Установите пакет pkg-config при помощи следующих команд:

Замечание

Известно, что в случае, когда с Popt-1.16 используется параметр ‘ —with-installed-popt ‘, возникают проблемы с выполнением фазы make.

Чтобы проверить результаты, выполните make check.

Теперь в роли root выполните:

Конфигурирование пакета pkg-config

Поскольку для установки пакета pkg-config используется префикс, то по умолчанию в качестве значения для PKG_CONFIG_PATH указывается /usr/lib/pkgconfig:/usr/share/pkgconfig . Вы можете добавить к переменной PKG_CONFIG_PATH дополнительные пути, в которых указано место установки в вашей системе файлов .pc . Обратите внимание, что переменная PKG_CONFIG_PATH нужна только во время компиляции пакетов, а не во время выполнения.

Описание пакета

Установленные программы: pkg-config

Установленные библиотеки: Нет

Установленные директории: Нет

возвращает метаинформацию об указанной библиотеке или пакете

Перевод сделан с варианта оригинала, датированного 2011-11-04 22:01:54 +0000

Источник

Pkg config install linux

Система сборки Gwyddion на Unix основана на GNU autotools (autoconf, automake, libtool), так же, как и большинство современного свободного программного обеспечения и программ с открытым исходным кодом под Unix. Если вы когда-либо собирали программы из исходников, вы, вероятно, уже встречались с autotools и знаете, что делать дальше. Этот раздел, тем не менее, будет описывать процесс сборки достаточно детально, чтобы быть понятным и тем, кто ещё этого не делал. Файл INSTALL в каталоге верхнего уровня архива с исходным кодом содержит общие инструкции по установке с помощью GNU autotools.

Краткие инструкции

Если вам уже знакома последовательность действий:

tar -jxvf gwyddion-2.49.tar.xz
cd gwyddion-2.49
./configure
make
make install

Распаковка исходного кода

Распакуйте архив с исходным кодом командой

tar -Jxvf gwyddion-2.49.tar.xz

заменяя 2.49 текущим номером версии. При этом будет создан каталог gwyddion-2.49 (снова с текущим номером версии вместо 2.49), перейдите с помощью cd в этот каталог. Все остальные действия по сборке будут проходить там.

Если в операционной системе отсутствует xz, можно загрузить gwyddion-2.49.tar.gz (сжатый с помощью gzip) вместо предыдущего архива и распаковать его с помощью

tar -zxvf gwyddion-2.49.tar.gz

Однако, современные Unix и подобные им системы поддерживают и gzip, и xz, и заметно меньший gwyddion-2.49.tar.xz обычно будет более удачным вариантом.

Настройка

чтобы сконфигурировать сборку Gwyddion .

Скрипт оболочки configure пытается угадать правильные значения для различных переменных, меняющихся от системы к системе и используемых в процессе компиляции. Он использует эти переменные чтобы создать Makefile в каждом каталоге пакета, набор заголовочных файлов с расширением .h , которые содержат зависящие от системы определения и некоторые другие вспомогательные файлы. В конце своей работы он создаёт другой скрипт оболочки config.status , который можно затем использовать для повторения текущей конфигурации, и файл config.log , который содержит подробности процесса детектирования и который полезно включать в сообщения об ошибках компиляции. В конце команда configure также выводит суммарную сводку о включенных и выключенных дополнительных опциях, включая причины почему опция была выключена.

Если configure пишет об отсутствии требуемых пакетов, установите эти пакеты и перезапустите её. То же самое справедливо и для случая, если configure заканчивается успешно, но вы обнаружили, что забыли установить опциональный компонент, с которым хотели собрать Gwyddion . Возможно, что пакет не был найден или был неправильно определён даже если вы его установили, а именно если он был установлен в нестандартный каталог. В этом случае необходимо настроить определённые переменные окружения чтобы дать configure возможность найти эти пакеты:

Большинство пакетов идут вместе с так называемыми файлами pkg-config ( .pc ), которые описывают как программы должны собираться и линковаться с ними. configure использует информацию из этих файлов, следовательно, PKG_CONFIG_PATH должна быть установлена таким образом, чтобы там были перечислены все нестандартные какталоги с нужными файлами pkg-config. Чтобы добавить, например, установленную библиотеку GTK+ в /opt/gnome и установленную библиотеку FFTW3 в $HOME/opt/fftw3 , нужно выполнить:

PKG_CONFIG_PATH=/opt/gnome/lib/pkgconfig:$HOME/opt/fftw3/lib/pkgconfig
export PKG_CONFIG_PATH

Может потребоваться настроить эти переменные чтобы включить нестандартные каталоги с исполняемыми файлами и библиотеками соответствующих пакетов. Переменные LD_LIBRARY_PATH и DYLD_LIBRARY_PATH обе задают путь поиска для разделяемых библиотек, но первая используется в системах на основе Linux и BSD, в то время, как вторая на OS X.

Может потребоваться настроить эти переменные чтобы включить нестандартные каталоги с заголовочными файлами и библиотеками пакетов, с которыми не шло файлов pkg-config, например, для libTIFF в /usr/local можно установить:

CPPFLAGS=-I/usr/local/include
export CPPFLAGS
LDFLAGS=-L/usr/local/lib
export LDFLAGS

Опция —prefix команды configure задаёт базовый каталог установки. Компоненты программы будут установлены в его подкаталоги bin , lib , share , и т.д. (которые будут созданы если они не существуют). Более детальное управление возможно с помощью опций, задающих отдельные подкаталоги, таких как —bindir , —libdir . Префикс по умолчанию – /usr/local/bin , чтобы установить Gwyddion в домашний каталог пользователя можно использовать, например команду

Читайте также:  Как настроить чувствительность мыши windows

Если вы устанавливаете Gwyddion для личного использования это является рекомендованным вариантом, поскольку в этом случае не требуется выполнять действий с правами суперпользователя.

Настройки процесса конфигурирования

Необязательные возможности можно включить/выключить с помощью опций вроде —with-foo / —without-foo или —enable-foo / —disable-foo . Например, компиляция с zlib может быть отключена командой:

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

Полный список опций и важных переменных configure можно получить с помощью команды:

Список будет длинным и большая часть опций контроллирует включение/выключение отдельных опциональных возможностей или передачу необходимых флагов компиляции и связывания для различных библиотек. Например, задавая FFTW3_CFLAGS и FFTW3_LIBS можно задать (или переопределить) как будет осуществляться компиляция и связывание с FFTW3. Однако, такое ручное задание является резервным вариантом для гораздо более удобного метода, основанного на использовании pkg-config в том случае если он почему-то не работает.

Некоторые интересные общие опции описаны в следующих параграфах.

Настройки пользователей

C Gwyddion поставляются различные файлы взаимодействия со средой рабочего стола, которые определяют типы MIME, элементы меню, привязки файлов, генерацию миниатюр и т.п. Если Gwyddion устанавливается в системный каталог, они обычно находятся в правильных местах файловой системы. Однако, если вы устанавливаете его куда-то в свой каталог пользователя, то эти файлы нужно поместить в другое место. а именно в определённые скрытые каталоги, начинающиеся с точки в вашем домашнем каталоге.

Это можно задать с помощью опции —enable-home-installation команды configure . Следует отметить, что использование этой опции приводит к установке файлов в каталоги вне заданного префикса.

Настройки создателей пакетов

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

Обновление файлов FreeDesktop может быть отключено с помощью —disable-desktop-file-update . Установка схем GConf2 может быть отключена с помощью —disable-schemas-install . Обычно это не надо делать в явной форме т.к. установки в временный каталог используют непустую переменную DESTDIR (см. раздел установка). Если переменная DESTDIR не пустая, система сборки пропустит автоматически действия после установки. Тем не менее, обычной причиной отключения этих действий является то. что Gwyddion устанавливается на временное место вместо финального каталога (что обычно происходит при сборке пакетов в Linux). В этом случае вспомогательные действия отключаются автоматически при непустой переменной DESTDIR (см. раздел установка) и, следовательно, нет нужды отключать их в configure .

Передавая параметр —enable-library-bloat скрипту configure заставляет связываться модулям со всеми библиотеками. Это автоматически включается на MS Windows, где это является обязательным требованием. В основанных на Unix системах, связывание модулей со всеми библиотеками, которые уже загружены основной программой только напрасно замедляет работу (как во время сборки, так и во время исполнения). Таким образом, модули не связываются непосредственно с основными библиотеками вроде GLib. если ваша система или правила сборки требуют связывания модулей со всеми библиотеками (например, в системах, основанных на AltLinux), использование этой опции включает данное поведение.

Передачей опции —disable-module-bundling команде configure можно запретить объединение всех модулей одного типа (файловых, обработки данных, . ) в одну разделяемую библиотеку, что обычно делается для сохранения места на диске и ускорения загрузки. Хотя подобное объединение не меняет функциональность, оно заметно меняет набор устанавливаемых файлов. Если вы, по той или иной причине, полагаетесь на наличие на диске файла gwyfile.so , самое время остановиться и перестать так делать. Тем не менее, можно использовать данную опцию чтобы принудительно получить традиционный вариант установки, где каждый модуль находился в отдельном файле.

Настройки для разработчиков

Если вы собираетесь накладывать патч или иным образом модифицировать исходный код Gwyddion запустите configure с опцией —enable-maintainer-mode чтобы включить различные правила обновления и пересборки, которые не используются при обычной компиляции. В зависимости от вида изменений могут понадобиться некоторые дополнительные инструменты, описанные в разделе Снимок Subversion, разработка.

По умолчанию справочное руководство по C API не пересобирается. Подготовленные файлы HTML распространяются с архивом, документация меняется редко и её генерация требует достаточно продолжительного времени. Для того, чтобы включить генерацию документации по API нужно передать опцию —enable-gtk-doc скрипту configure . Естественно, вам потребуется gtk-doc. Следует отметить, что configure предупредит вас, если вы включили режим мантейнера, но выключили gtk-doc (что может быть полезно для того, чтобы не пересобирать постоянно и бесцельно документацию). Если вы не собираетесь делать make dist , это предупреждение безвредно.

Источник

pkg-config(1) — Linux man page

pkg-config — Return metainformation about installed libraries

Synopsis

pkg-config [—modversion] [—help] [—print-errors] [—silence-errors] [—cflags] [—libs] [—libs-only-L] [—libs-only-l] [—cflags-only-I] [—variable=VARIABLENAME] [—define-variable=VARIABLENAME=VARIABLEVALUE] [—uninstalled] [—exists] [—atleast-version=VERSION] [—exact-version=VERSION] [—max-version=VERSION] [LIBRARIES. ]

Description

The pkg-config program is used to retrieve information about installed libraries in the system. It is typically used to compile and link against one or more libraries. Here is a typical usage scenario in a Makefile: cc program.c ‘pkg-config —cflags —libs gnomeui’ pkg-config retrieves information about packages from special metadata files. These files are named after the package, with the extension .pc. By default, pkg-config looks in the directory prefix/lib/pkgconfig for these files; it will also look in the colon-separated (on Windows, semicolon-separated) list of directories specified by the PKG_CONFIG_PATH environment variable.

The package name specified on the pkg-config command line is defined to be the name of the metadata file, minus the .pc extension. If a library can install multiple versions simultaneously, it must give each version its own name (for example, GTK 1.2 might have the package name «gtk+» while GTK 2.0 has «gtk+-2.0»).

Options

The following options are supported: —modversion Requests that the version information of the libraries specified on the command line be displayed. If pkg-config can find all the libraries on the command line, each library’s version string is printed to stdout, one version per line. In this case pkg-config exits successfully. If one or more libraries is unknown, pkg-config exits with a nonzero code, and the contents of stdout are undefined. —help

Читайте также:  Анлок windows phone что это

Displays a help message and terminates. —print-errors If one or more of the modules on the command line, or their dependencies, are not found, or if an error occurs in parsing a .pc file, then this option will cause errors explaining the problem to be printed. With «predicate» options such as «—exists» pkg-config runs silently by default, because it’s usually used in scripts that want to control what’s output. This option can be used alone (to just print errors encountered locating modules on the command line) or with other options. The PKG_CONFIG_DEBUG_SPEW environment variable overrides this option. —silence-errors If one or more of the modules on the command line, or their dependencies, are not found, or if an error occurs in parsing a a .pc file, then this option will keep errors explaining the problem from being printed. With «predicate» options such as «—exists» pkg-config runs silently by default, because it’s usually used in scripts that want to control what’s output. So this option is only useful with options such as «—cflags» or «—modversion» that print errors by default. The PKG_CONFIG_DEBUG_SPEW environment variable overrides this option. —errors-to-stdout If printing errors, print them to stdout rather than the default stderr The following options are used to compile and link programs: —cflags This prints pre-processor and compile flags required to compile the packages on the command line, including flags for all their dependencies. Flags are «compressed» so that each identical flag appears only once. pkg-config exits with a nonzero code if it can’t find metadata for one or more of the packages on the command line. —libs

This option is identical to «—cflags», only it prints the link flags. As with «—cflags», duplicate flags are merged (maintaining proper ordering), and flags for dependencies are included in the output. —libs-only-L This prints the -L/-R part of «—libs». That is, it defines the library search path but doesn’t specify which libraries to link with. —libs-only-l This prints the -l part of «—libs» for the libraries specified on the command line. Note that the union of «—libs-only-l» and «—libs-only-L» may be smaller than «—libs», due to flags such as -rdynamic. —variable=VARIABLENAME This returns the value of a variable defined in a package’s .pc file. Most packages define the variable «prefix», for example, so you can say: —define-variable=VARIABLENAME=VARIABLEVALUE This sets a global value for a variable, overriding the value in any .pc files. Most packages define the variable «prefix», for example, so you can say: —uninstalled Normally if you request the package «foo» and the package «foo-uninstalled» exists, pkg-config will prefer the «-uninstalled» variant. This allows compilation/linking against uninstalled packages. If you specify the «—uninstalled» option, pkg-config will return successfully if any «-uninstalled» packages are being used, and return failure (false) otherwise. (The «PKG_CONFIG_DISABLE_UNINSTALLED» environment variable keeps pkg-config from implicitly choosing «-uninstalled» packages, so if that variable is set, they will only have been used if you pass a name like «foo-uninstalled» on the command line explicitly.) —exists —atleast-version=VERSION —exact-version=VERSION —max-version=VERSION These options test whether the package or list of packages on the command line are known to pkg-config, and optionally whether the version number of a package meets certain contraints. If all packages exist and meet the specified version constraints, pkg-config exits successfully. Otherwise it exits unsuccessfully.

Rather than using the version-test options, you can simply give a version constraint after each package name, for example: Remember to use —print-errors if you want error messages. —msvc-syntax This option is available only on Windows. It causes pkg-config to output -l and -L flags in the form recognized by the Microsoft Visual C++ command-line compiler, cl. Specifically, instead of -Lx:/some/path it prints /libpath:x/some/path, and instead of -lfoo it prints foo.lib. Note that the —libs output consists of flags for the linker, and should be placed on the cl command line after a /link switch. —dont-define-prefix This option is available only on Windows. It prevents pkg-config from automatically trying to override the value of the variable «prefix» in each .pc file. —prefix-variable=PREFIX Also this option is available only on Windows. It sets the name of the variable that pkg-config automatically sets as described above. —static Output libraries suitable for static linking. That means including any private libraries in the output. This relies on proper tagging in the .pc files, else a too large number of libraries will ordinarily be output.

Environment Variables

PKG_CONFIG_PATH A colon-separated (on Windows, semicolon-separated) list of directories to search for .pc files. The default directory will always be searched after searching the path; the default is libdir/pkgconfig:datadir/pkgconfig where libdir is the libdir where pkg-config and datadir is the datadir where pkg-config was installed. PKG_CONFIG_DEBUG_SPEW If set, causes pkg-config to print all kinds of debugging information and report all errors. PKG_CONFIG_TOP_BUILD_DIR A value to set for the magic variable pc_top_builddir which may appear in .pc files. If the environment variable is not set, the default value ‘$(top_builddir)’ will be used. This variable should refer to the top builddir of the Makefile where the compile/link flags reported by pkg-config will be used. This only matters when compiling/linking against a package that hasn’t yet been installed. PKG_CONFIG_DISABLE_UNINSTALLED Normally if you request the package «foo» and the package «foo-uninstalled» exists, pkg-config will prefer the «-uninstalled» variant. This allows compilation/linking against uninstalled packages. If this environment variable is set, it disables said behavior. PKG_CONFIG_ALLOW_SYSTEM_CFLAGS Don’t strip -I/usr/include out of cflags. PKG_CONFIG_ALLOW_SYSTEM_LIBS Don’t strip -L/usr/lib out of libs PKG_CONFIG_SYSROOT_DIR Modify -I and -L to use the directories located in target sysroot. this option is usefull when crosscompiling package that use pkg-config to determine CFLAGS anf LDFLAGS. -I and -L are modified to point to the new system root. this means that a -I/usr/include/libfoo will become -I/var/target/usr/include/libfoo with a PKG_CONFIG_SYSROOT_DIR equal to /var/target (same rule apply to -L) PKG_CONFIG_LIBDIR Replaces the default pkg-config search directory.

Читайте также:  Пользователь пк с нуля windows 10

Windows Specialities

If a .pc file is found in a directory that matches the usual conventions (i.e., ends with \lib\pkgconfig), the prefix for that package is assumed to be the grandparent of the directory where the file was found, and the prefix variable is overridden for that file accordingly.

In addition to the PKG_CONFIG_PATH environment variable, the Registry keys HKEY_CURRENT_USER\Software\pkgconfig\PKG_CONFIG_PATH and HKEY_LOCAL_MACHINE\Software\pkgconfig\PKG_CONFIG_PATH can be used to specify directories to search for .pc files. Each (string) value in these keys is treated as a directory where to look for .pc files.

Autoconf Macros

PKG_CHECK_MODULES(VARIABLE-PREFIX,MODULES[,ACTION-IF-FOUND,[ACTION-IF-NOT-FOUND]]) The macro PKG_CHECK_MODULES can be used in configure.ac to check whether modules exist. A typical usage would be: This would result in MYSTUFF_LIBS and MYSTUFF_CFLAGS substitution variables, set to the libs and cflags for the given module list. If a module is missing or has the wrong version, by default configure will abort with a message. To replace the default action, specify an ACTION-IF-NOT-FOUND. PKG_CHECK_MODULES will not print any error messages if you specify your own ACTION-IF-NOT-FOUND. However, it will set the variable MYSTUFF_PKG_ERRORS, which you can use to display what went wrong.

Note that if there is a possibility the first call to PKG_CHECK_MODULES might not happen, you should be sure to include an explicit call to PKG_PROG_PKG_CONFIG in your configure.ac

Defines the PKG_CONFIG variable to the best pkg-config available, useful if you need pkg-config but don’t want to use PKG_CHECK_MODULES.

PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])

Check to see whether a particular set of modules exists. Similar to PKG_CHECK_MODULES(), but does not set variables or print errors.

Similar to PKG_CHECK_MODULES, make sure that the first instance of this or PKG_CHECK_MODULES is called, or make sure to call PKG_CHECK_EXISTS manually

Metadata File Syntax

To add a library to the set of packages pkg-config knows about, simply install a .pc file. You should install this file to libdir/pkgconfig.

Here is an example file: You would normally generate the file using configure, of course, so that the prefix, etc. are set to the proper values.

Files have two kinds of line: keyword lines start with a keyword plus a colon, and variable definitions start with an alphanumeric string plus an equals sign. Keywords are defined in advance and have special meaning to pkg-config; variables do not, you can have any variables that you wish (however, users may expect to retrieve the usual directory name variables).

Note that variable references are written «$«; you can escape literal «$<" as "$$<". Name:

This field should be a human-readable name for the package. Note that it is not the name passed as an argument to pkg-config. Description: This should be a brief description of the package URL:

An URL where people can get more information about and download the package Version: This should be the most-specific-possible package version string. Requires: This is a comma-separated list of packages that are required by your package. Flags from dependent packages will be merged in to the flags reported for your package. Optionally, you can specify the version of the required package (using the operators =, , >=, Conflicts: This optional line allows pkg-config to perform additional sanity checks, primarily to detect broken user installations. The syntax is the same as Requires: except that you can list the same package more than once here, for example «foobar = 1.2.3, foobar = 1.2.5, foobar >= 1.3», if you have reason to do so. If a version isn’t specified, then your package conflicts with all versions of the mentioned package. If a user tries to use your package and a conflicting package at the same time, then pkg-config will complain. Libs:

This line should give the link flags specific to your package. Don’t add any flags for required packages; pkg-config will add those automatically. Libs.private: This line should list any private libraries in use. Private libraries are libraries which are not exposed through your library, but are needed in the case of static linking. Cflags: This line should list the compile flags specific to your package. Don’t add any flags for required packages; pkg-config will add those automatically.

Author

pkg-config was written by James Henstridge, rewritten by Martijn van Beers, and rewritten again by Havoc Pennington. Tim Janik, Owen Taylor, and Raja Harinath submitted suggestions and some code. gnome-config was written by Miguel de Icaza, Raja Harinath and various hackers in the GNOME team. It was inspired by Owen Taylor’s gtk-config program.

pkg-config does not handle mixing of parameters with and without = well. Stick with one.

Источник

Оцените статью