pkg config что это
pkg-config
James Henstridge; переписана Хэвоком Пеннингтоном
2006-12-11 ; 2192 days ago or earlier
Эта программа выводит информацию об установленных библиотеках, которая включает в себя:
Как это работает
Эти записи, как правило, содержат список библиотек и заголовочных файлов, которые могут потребоваться при компиляции других программ. Кроме того, в них может содержаться версия библиотеки и её описание.
В этом примере в файле описаны пути к библиотекам (/usr/local/lib) и их заголовочным файлам в (/usr/local/include). Также в нём описано название библиотеки (libpng) и его версия (1.2.8). Кроме всего прочего, в файле описаны дополнительные опции компилятора и компоновщика, которые понадобятся при компиляции программ.
При сборке программы удобно использовать pkg-config следующим образом:
Ссылки
Полезное
Смотреть что такое «pkg-config» в других словарях:
pkg-config — Aktuelle Version 0.25 (Mai 2010) Programmiersprache C Kategorie Programmierwerkzeug Lizenz GPL … Deutsch Wikipedia
Pkg-config — (von engl. package, „Paket“ und config, „Konfiguration“) ist ein Computerprogramm, das eine einheitliche Schnittstelle zur Abfrage von Metadaten über beliebige Software bereitstellt. pkg config wird in erster Linie für die Versionsverwaltung… … Deutsch Wikipedia
Pkg-config — Développeur Tollef Fog Heen / freedesktop.org Écrit en … Wikipédia en Français
Pkg-config — Saltar a navegación, búsqueda pkg config es un software de ordenador que provée una interfaz unificada para llamar librerías instaladas cuando se está compilando un programa a partir del código fuente. pkg config fue diseñado originalmente para… … Wikipedia Español
Pkg-config — is a piece of computer software that provides a unified interface for querying installed libraries for the purpose of compiling software from its source code. pkg config was originally designed for Linux but is now also available for the various… … Wikipedia
Autoconf — Programmablaufplan von autoconf und automake, zwei Tools im GNU Build System Das GNU Build System, auch bekannt als Autotools, ist eine Sammlung von Tools für die Computerprogrammierung, die vom GNU Projekt entwickelt wurden. Diese Tools sind für … Deutsch Wikipedia
Autoheader — Programmablaufplan von autoconf und automake, zwei Tools im GNU Build System Das GNU Build System, auch bekannt als Autotools, ist eine Sammlung von Tools für die Computerprogrammierung, die vom GNU Projekt entwickelt wurden. Diese Tools sind für … Deutsch Wikipedia
Automake — Programmablaufplan von autoconf und automake, zwei Tools im GNU Build System Das GNU Build System, auch bekannt als Autotools, ist eine Sammlung von Tools für die Computerprogrammierung, die vom GNU Projekt entwickelt wurden. Diese Tools sind für … Deutsch Wikipedia
Autotools — Programmablaufplan von autoconf und automake, zwei Tools im GNU Build System Das GNU Build System, auch bekannt als Autotools, ist eine Sammlung von Tools für die Computerprogrammierung, die vom GNU Projekt entwickelt wurden. Diese Tools sind für … Deutsch Wikipedia
Configure — Programmablaufplan von autoconf und automake, zwei Tools im GNU Build System Das GNU Build System, auch bekannt als Autotools, ist eine Sammlung von Tools für die Computerprogrammierung, die vom GNU Projekt entwickelt wurden. Diese Tools sind für … Deutsch Wikipedia
Национальная библиотека им. Н. Э. Баумана
Bauman National Library
Персональные инструменты
pkg-config
Он выводит различную информацию об установленных библиотеках. Эта информация может включать:
Первая реализация была написана в shell. Позднее она была переписана на C,с использованием библиотеки GLib.
Содержание
Описание
Когда библиотека установлена (автоматически с использованием RPM, deb или другой системы двоичной упаковки или путем компиляции из исходного кода), файл .pc должен быть включен и помещен в каталог с другими .pc (точный каталог зависит от вашей системы и указывается в man-странице pkg-config). Этот файл имеет несколько записей.
Эти записи обычно содержат список зависимых библиотек, которые также необходимо компилировать программам, использующим пакет. Записи также обычно включают расположение файлов заголовков, информацию о версии и описание.
Ниже приводится краткое описание полей ключевых слов.
Написание файлов pkg-config
При создании файлов pkg-config для пакета сначала необходимо решить, как они будут распространяться. Каждый файл лучше всего использовать для описания одной библиотеки, поэтому каждый пакет должен иметь как минимум столько файлов pkg-config, сколько они устанавливают библиотек.
Поля «Name», «Description» и «URL» являются чисто информационными и должны быть легко заполнены. Поле « Version» немного сложнее, чтобы обеспечить его использование потребителями данных. Pkg-config использует алгоритм RPM для сравнения версий. Это лучше всего работает с десятичным числом с точками, таким как 1.2.3, поскольку буквы могут вызвать неожиданные результаты. Число должно монотонно возрастать и быть максимально конкретным при описании библиотеки. Обычно здесь достаточно использовать номер версии пакета, поскольку отслеживать его легко.
Прежде чем описывать более полезные поля, будем демонстрировать определения переменных. Чаще всего используется определение путей установки, чтобы они не загромождали поля метаданных. Поскольку переменные рекурсивно разворачиваются, это очень полезно при использовании в сочетании с производными путями autoconf.
Наиболее важными полями метаданных pkg-config являются Requires, Requires.private, Cflags, Libs и Libs.private. Они будут определять метаданные, используемые внешними проектами, для компиляции и связывания с библиотекой.
Requires and Requires.private определяет другие модули, необходимые библиотеке. Обычно предпочитается использовать частный вариант Requires, чтобы не подвергать ненужные библиотеки программе, которая связывается с вашей библиотекой. Если программа не будет использовать символы требуемой библиотеки, она не должна связываться непосредственно с этой библиотекой. См. Обсуждение перевязки для более подробного объяснения.
Поскольку pkg-config всегда предоставляет флаги ссылок в библиотеках Requires, эти модули станут прямыми зависимостями программы. С другой стороны, библиотеки из Requires.private будут включены только при статической привязке. По этой причине обычно бывает целесообразно добавлять модули из одного пакета в Requires.
Поле Libs содержит флаги ссылок, необходимые для использования этой библиотеки. Кроме того, Libs и Libs.private содержат флаги ссылок для других библиотек, не поддерживаемых pkg-config. Как и в поле Requires, предпочтительно добавлять флаги ссылок для внешних библиотек в поле Libs.private, чтобы программы не приобретали дополнительную прямую зависимость.
Наконец, Cflags содержит флаги компилятора для использования библиотеки. В отличие от поля Libs, нет частного варианта Cflags. Это связано с тем, что типы данных и определения макросов необходимы независимо от сценария связывания.
Использование файлов pkg-config
Pkg config что это
Система сборки Gwyddion на Unix основана на GNU autotools (autoconf, automake, libtool), так же, как и большинство современного свободного программного обеспечения и программ с открытым исходным кодом под Unix. Если вы когда-либо собирали программы из исходников, вы, вероятно, уже встречались с autotools и знаете, что делать дальше. Этот раздел, тем не менее, будет описывать процесс сборки достаточно детально, чтобы быть понятным и тем, кто ещё этого не делал. Файл INSTALL в каталоге верхнего уровня архива с исходным кодом содержит общие инструкции по установке с помощью GNU autotools.
Краткие инструкции
Если вам уже знакома последовательность действий:
Распаковка исходного кода
Распакуйте архив с исходным кодом командой
заменяя 2.49 текущим номером версии. При этом будет создан каталог gwyddion-2.49 (снова с текущим номером версии вместо 2.49), перейдите с помощью cd в этот каталог. Все остальные действия по сборке будут проходить там.
Если в операционной системе отсутствует xz, можно загрузить gwyddion-2.49.tar.gz (сжатый с помощью gzip) вместо предыдущего архива и распаковать его с помощью
Однако, современные Unix и подобные им системы поддерживают и gzip, и xz, и заметно меньший gwyddion-2.49.tar.xz обычно будет более удачным вариантом.
Настройка
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
Если вы устанавливаете Gwyddion для личного использования это является рекомендованным вариантом, поскольку в этом случае не требуется выполнять действий с правами суперпользователя.
Настройки процесса конфигурирования
По умолчанию все опциональные возможности включены, если найдены все требуемые для их реализации библиотеки. Краткая информация о включенных и отключенных опциональных возможностях печатается в выводе команды configure недалеко от его конца.
Полный список опций и важных переменных configure можно получить с помощью команды:
Список будет длинным и большая часть опций контроллирует включение/выключение отдельных опциональных возможностей или передачу необходимых флагов компиляции и связывания для различных библиотек. Например, задавая FFTW3_CFLAGS и FFTW3_LIBS можно задать (или переопределить) как будет осуществляться компиляция и связывание с FFTW3. Однако, такое ручное задание является резервным вариантом для гораздо более удобного метода, основанного на использовании pkg-config в том случае если он почему-то не работает.
Некоторые интересные общие опции описаны в следующих параграфах.
Настройки пользователей
C Gwyddion поставляются различные файлы взаимодействия со средой рабочего стола, которые определяют типы MIME, элементы меню, привязки файлов, генерацию миниатюр и т.п. Если Gwyddion устанавливается в системный каталог, они обычно находятся в правильных местах файловой системы. Однако, если вы устанавливаете его куда-то в свой каталог пользователя, то эти файлы нужно поместить в другое место. а именно в определённые скрытые каталоги, начинающиеся с точки в вашем домашнем каталоге.
Настройки создателей пакетов
Если Gwyddion устанавливается во временный каталог для дальнейшего создания пакета, необходимо отключить определённые действия после установки, которые нужно производить с системой, где пакет будет установлен, а не в момент создания пакета.
Настройки для разработчиков
Guide to pkg-config
Dan Nicholson
Overview
This document aims to give an overview to using the pkg-config tool from the perspective of both a user and a developer. It reviews the concepts behind pkg-config, how to write pkg-config files to support your project, and how to use pkg-config to integrate with 3rd party projects.
More information on pkg-config can be found at the website and in the pkg-config(1) manual page.
This document assumes usage of pkg-config on a Unix-like operating system such as Linux. Some of the details may be different on other platforms.
Modern computer systems use many layered components to provide applications to the user. One of the difficulties in assembling these parts is properly integrating them. pkg-config collects metadata about the installed libraries on the system and easily provides it to the user.
Without a metadata system such as pkg-config, it can be very difficult to locate and obtain details about the services provided on a given computer. For a developer, installing pkg-config files with your package greatly eases adoption of your API.
Concepts
The primary use of pkg-config is to provide the necessary details for compiling and linking a program to a library. This metadata is stored in pkg-config files. These files have the suffix .pc and reside in specific locations known to the pkg-config tool. This will be described in more detail later.
The file format contains predefined metadata keywords and freeform variables. An example may be illustrative:
The keyword definitions such as Name: begin with a keyword followed by a colon and the value. The variables such as prefix= are a string and value separated by an equals sign. The keywords are defined and exported by pkg-config. The variables are not necessary, but can be used by the keyword definitions for flexibility or to store data not covered by pkg-config.
Here is a short description of the keyword fields. A more in depth description of these fields and how to use them effectively will be given in the Writing pkg-config files section.
Writing pkg-config files
When creating pkg-config files for a package, it is first necessary to decide how they will be distributed. Each file is best used to describe a single library, so each package should have at least as many pkg-config files as they do installed libraries.
The package name is determined through the filename of the pkg-config metadata file. This is the portion of the filename prior to the .pc suffix. A common choice is to match the library name to the .pc name. For instance, a package installing libfoo.so would have a corresponding libfoo.pc file containing the pkg-config metadata. This choice is not necessary; the .pc file should simply be a unique identifier for your library. Following the above example, foo.pc or foolib.pc would probably work just as well.
The Name, Description and URL fields are purely informational and should be easy to fill in. The Version field is a bit trickier to ensure that it is usable by consumers of the data. pkg-config uses the algorithm from RPM for version comparisons. This works best with a dotted decimal number such as 1.2.3 since letters can cause unexpected results. The number should be monotonically increasing and be as specific as possible in describing the library. Usually it’s sufficient to use the package’s version number here since it’s easy for consumers to track.
Before describing the more useful fields, it will be helpful to demonstrate variable definitions. The most common usage is to define the installation paths so that they don’t clutter the metadata fields. Since the variables are expanded recursively, this is very helpful when used in conjunction with autoconf derived paths.
The most important pkg-config metadata fields are Requires, Requires.private, Cflags, Libs and Libs.private. They will define the metadata used by external projects to compile and link with the library.
Requires and Requires.private define other modules needed by the library. It is usually preferred to use the private variant of Requires to avoid exposing unnecessary libraries to the program that is linking with your library. If the program will not be using the symbols of the required library, it should not be linking directly to that library. See the discussion of overlinking for a more thorough explanation.
Since pkg-config always exposes the link flags of the Requires libraries, these modules will become direct dependencies of the program. On the other hand, libraries from Requires.private will only be included when static linking. For this reason, it is usually only appropriate to add modules from the same package in Requires.
The Libs field contains the link flags necessary to use that library. In addition, Libs and Libs.private contain link flags for other libraries not supported by pkg-config. Similar to the Requires field, it is preferred to add link flags for external libraries to the Libs.private field so programs do not acquire an additional direct dependency.
Finally, the Cflags contains the compiler flags for using the library. Unlike the Libs field, there is not a private variant of Cflags. This is because the data types and macro definitions are needed regardless of the linking scenario.
Using pkg-config files
Consider a system with two modules, foo and bar. Their .pc files might look like this:
The version of the modules can be obtained with the --modversion option.
To print the link flags needed for each module, use the --libs option.
Notice that pkg-config has suppressed part of the Libs field for both modules. This is because it treats the -L flag specially and knows that the $ directory /usr/lib is part of the system linker search path. This keeps pkg-config from interfering with the linker operation.
Also, although foo is required by bar, the link flags for foo are not output. This is because foo is not directly needed by an application that only wants to use the bar library. For statically linking a bar application, we need both sets of linker flags:
pkg-config needs to output both sets of link flags in this case to ensure that the statically linked application will find all the necessary symbols. On the other hand, it will always output all the Cflags.
Another useful option, --exists, can be used to test for a module's availability.
One of the nicest features of pkg-config is providing version checking. It can be used to determine if a sufficient version is available.
Some commands will provide more verbose output when combined with the --print-errors option.
The message above references the PKG_CONFIG_PATH environment variable. This variable is used to augment pkg-config's search path. On a typical Unix system, it will search in the directories /usr/lib/pkgconfig and /usr/share/pkgconfig. This will usually cover system installed modules. However, some local modules may be installed in a different prefix such as /usr/local. In that case, it's necessary to prepend the search path so that pkg-config can locate the .pc files.
A few autoconf macros are also provided to ease integration of pkg-config modules into projects.
Frequently asked questions
The pkg-config output can easily be used on the compiler command line. Assuming the x library has a x.pc pkg-config file:
The integration can be more robust when used with autoconf and automake. By using the supplied PKG_CHECK_MODULES macro, the metadata is easily accessed in the build process.
If the x module is found, the macro will fill and substitute the X_CFLAGS and X_LIBS variables. If the module is not found, an error will be produced. Optional 3rd and 4th arguments can be supplied to PKG_CHECK_MODULES to control actions when the module is found or not.
If the x library has pkg-config support, add it to the Requires.private field. If it does not, augment the Cflags field with the necessary compiler flags for using the libx headers. In either case, pkg-config will output the compiler flags when --static is used or not.
Again, add the module to Requires.private if it supports pkg-config. In this case, the compiler flags will be emitted unnecessarily, but it ensures that the linker flags will be present when linking statically. If libx does not support pkg-config, add the necessary linker flags to Libs.private.
Copyright (C) 2010 Dan Nicholson.
This document is licensed under the GNU General Public License, Version 2 or any later version.
pkg-config
pkg-config is a helper tool which is used to obtain compiler & linker flags when building a package depending on a library.
Contents
Differences from other solutions
libtool archives (.la files)
Implicit vs explicit use
Static vs dynamic linking
libtool provides no distinction between dynamic and static linking. In both cases, the complete list of dependant libraries is passed to linker.
pkg-config explicitly distinguishes between public and private dependencies. This way, when using dynamic linking only actually necessary libraries are passed to linker; and when using static linking, the complete list is used.
Build system-agnostic
libtool archives are usually useful only when libtool is used both to build the library and the final executable. pkg-config is designed to be build system-agnostic instead.
No absolute paths
For a long time Gentoo suffered an issue that libtool archives contained absolute paths to dependent library archives. Effectively, whenever libraries were moved to another library directory, all libraries depending on them became broken and required rebuild. Although the issue is currently worked-around in Gentoo by replacing absolute paths with relative library names, it is still the upstream behavior of libtool.
pkg-config expresses dependencies through package names, and thus is free by design of similar issues.
Custom -config applications
Many libraries provide custom applications of similar function, for example pcap-config. Those applications are compiled along with the library, and often have the relevant compiler & linker flags compiled into itself.
Cross-compilation support
Usually, custom -config applications are built for the specific platform the library is built for. Effectively, they are of no use when cross-compiling if the host is unable to execute code for the target platform.
pkg-config uses simple text files which are platform-independent. Thus, for cross-compilation to work it is only necessary to install pkg-config on the host system and set appropriate PKG_CONFIG_PATH.
Available implementations
In the past, various implementations of pkg-config could be obtained via virtual/pkgconfig. Now only dev-util/pkgconf, a reimplementation in ANSI C, is available.