Build pkg config windows

Национальная библиотека им. Н. Э. Баумана
Bauman National Library

Персональные инструменты

pkg-config

pkg-config

Создатели: James Henstridge; rewritten by Havoc Pennington
Разработчики: Tollef Fog Heen / freedesktop.org
Выпущена: 2000 ; 21 years ago ( 2000 ) or earlier
Постоянный выпуск: 0.29 / 27 September 2015 года ; 5 years ago ( 2015-09-27 )
Написана на: C
Операционная система: Unix-like
Тип ПО: Programming tool
Лицензия: GNU GPL
Веб-сайт pkgconfig .freedesktop .org

pkg-config — это компьютерная программа, предоставляющая унифицированный интерфейс для опроса установленных библиотек с целью компилирования программного обеспечения из его исходного кода. Это позволяет программистам и сценариям установки работать без явного знания подробной информации о пути к библиотеке. Pkg-config первоначально был разработан для Linux, но теперь он также доступен для различных операционных систем BSD,Microsoft Windows, Mac OS X и Solaris.

Он выводит различную информацию об установленных библиотеках. Эта информация может включать:

  • Параметры для компилятора C или C ++
  • Параметры для компоновщика
  • Версия рассматриваемого пакета

Первая реализация была написана в shell. Позднее она была переписана на C,с использованием библиотеки GLib.

Содержание

Описание

Когда библиотека установлена (автоматически с использованием RPM, deb или другой системы двоичной упаковки или путем компиляции из исходного кода), файл .pc должен быть включен и помещен в каталог с другими .pc (точный каталог зависит от вашей системы и указывается в man-странице pkg-config). Этот файл имеет несколько записей.

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

Такие переменные как Name начинаются с ключевого слова, сопровождаемого двоеточием, и значения. Такие переменные, как prefix =, являются строкой, а значение — знаком равенства. Ключевые слова определены и экспортированы pkg-config. Переменные не нужны, но могут использоваться определениями ключевых слов для гибкости или для хранения данных, не охваченных pkg-config.

Ниже приводится краткое описание полей ключевых слов.

  • Name: читаемое человеком имя библиотеки или пакета. Это не влияет на использование инструмента pkg-config, который использует имя файла .pc.
  • Description: Краткое описание пакета.
  • URL: URL, где люди могут получить дополнительную информацию и загрузить пакет.
  • Version: строка, определяющая версию пакета.
  • Requires: список пакетов, необходимых для этого пакета. Версии этих пакетов могут быть указаны с помощью операторов сравнения =, , =.
  • Requires.private: Список частных пакетов, необходимых для этого пакета, но не предназначенных для приложений. Здесь также применяются правила, специфичные для версии, из поля Requires.
  • Conflicts: необязательное поле, описывающее пакеты, с которыми конфликтует этот. Здесь также применяются правила, специфичные для версии, из поля Requires. Это поле также принимает несколько экземпляров одного и того же пакета. Например, Conflicts: bar = 1.3.0.
  • Cflags: флаги компилятора, специфичные для этого пакета, и любые требуемые библиотеки, которые не поддерживают pkg-config. Если требуемые библиотеки поддерживают pkg-config, их следует добавить в Requires или Requires.private.
  • Libs: флаги ссылок, специфичные для этого пакета, и любые необходимые библиотеки, которые не поддерживают pkg-config. Здесь применяется то же правило, что и Cflags.
  • Libs.private: флаги ссылок для частных библиотек, которые требуются для этого пакета, но не для приложений. Здесь применяется то же правило, что и Cflags.

Написание файлов pkg-config

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

Имя пакета определяется через имя файла файла метаданных pkg-config. Это часть имени файла перед суффиксом .pc. Общий выбор — совместить имя библиотеки с именем .pc. Например, пакет, устанавливающий libfoo.so, будет иметь соответствующий файл libfoo.pc, содержащий метаданные pkg-config. Этот выбор не нужен; Файл .pc должен быть просто уникальным идентификатором для вашей библиотеки. Следуя приведенному выше примеру, foo.pc или foolib.pc, вероятно, будут работать так же хорошо.

Поля «Name», «Description» и «URL» являются чисто информационными и должны быть легко заполнены. Поле « Version» немного сложнее, чтобы обеспечить его использование потребителями данных. Pkg-config использует алгоритм RPM для сравнения версий. Это лучше всего работает с десятичным числом с точками, таким как 1.2.3, поскольку буквы могут вызвать неожиданные результаты. Число должно монотонно возрастать и быть максимально конкретным при описании библиотеки. Обычно здесь достаточно использовать номер версии пакета, поскольку отслеживать его легко.

Читайте также:  Принтер определяется как дисковод windows 10

Прежде чем описывать более полезные поля, будем демонстрировать определения переменных. Чаще всего используется определение путей установки, чтобы они не загромождали поля метаданных. Поскольку переменные рекурсивно разворачиваются, это очень полезно при использовании в сочетании с производными путями 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

Предполагая, что в системе установлены файлы .pc, инструмент pkg-config используется для извлечения метаданных для использования. Краткое описание параметров можно увидеть, выполнив

Рассмотрим систему с двумя модулями: foo и bar. Их .pc-файлы могут выглядеть так:

Версии модулей можно получить с помощью опции —modversion.

Чтобы напечатать флаги ссылок, необходимые для каждого модуля, используйте параметр —libs.

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.

  • Name: A human-readable name for the library or package. This does not affect usage of the pkg-config tool, which uses the name of the .pc file.
  • Description: A brief description of the package.
  • URL: An URL where people can get more information about and download the package.
  • Version: A string specifically defining the version of the package.
  • Requires: A list of packages required by this package. The versions of these packages may be specified using the comparison operators =, , =.
  • Requires.private: A list of private packages required by this package but not exposed to applications. The version specific rules from the Requires field also apply here.
  • Conflicts: An optional field describing packages that this one conflicts with. The version specific rules from the Requires field also apply here. This field also takes multiple instances of the same package. E.g., Conflicts: bar = 1.3.0.
  • Cflags: The compiler flags specific to this package and any required libraries that don’t support pkg-config. If the required libraries support pkg-config, they should be added to Requires or Requires.private.
  • Libs: The link flags specific to this package and any required libraries that don’t support pkg-config. The same rule as Cflags applies here.
  • Libs.private: The link flags for private libraries required by this package but not exposed to applications. The same rule as Cflags applies here.
Читайте также:  Что значит окно windows

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.

Читайте также:  Драйвера для видеокарты nvidia geforce gtx 750 ti для windows 10

Using pkg-config files

Assuming that there are .pc files installed on the system, the pkg-config tool is used to extract the metadata for usage. A short description of the options can be seen by executing pkg-config --help. A more in depth discussion can be found in the pkg-config(1) manual page. This section will provide a brief explanation of common usages.

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.

  • PKG_PROG_PKG_CONFIG([MIN-VERSION]): Locates the pkg-config tool on the system and checks the version for compatibility.
  • PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]): Checks to see whether a particular set of modules exists.
  • PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]): Checks to see whether a particular set of modules exists. If so, it sets _CFLAGS and _LIBS according to the output from pkg-config --cflags and pkg-config --libs.

Frequently asked questions

  1. My program uses library x. What do I do?

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.

My library z installs header files which include libx headers. What do I put in my z.pc file?

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.

My library z uses libx internally, but does not expose libx data types in its public API. What do I put in my z.pc file?

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.

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