What is linux ldconfig

ldconfig(8) — Linux man page

ldconfig — configure dynamic linker run-time bindings

Synopsis

/sbin/ldconfig [ -nNvXV ] [ -f conf ] [ -C cache ] [ -r root ] directory .
/sbin/ldconfig -l
[ -v ] library .
/sbin/ldconfig -p

Description

ldconfig creates the necessary links and cache to the most recent shared libraries found in the directories specified on the command line, in the file /etc/ld.so.conf, and in the trusted directories (/lib and /usr/lib). The cache is used by the run-time linker, ld.so or ld-linux.so. ldconfig checks the header and filenames of the libraries it encounters when determining which versions should have their links updated.

ldconfig will attempt to deduce the type of ELF libs (i.e., libc5 or libc6/glibc) based on what C libs, if any, the library was linked against.

Some existing libs do not contain enough information to allow the deduction of their type. Therefore, the /etc/ld.so.conf file format allows the specification of an expected type. This is only used for those ELF libs which we can not work out. The format is «dirname=TYPE», where TYPE can be libc4, libc5, or libc6. (This syntax also works on the command line.) Spaces are not allowed. Also see the -p option. ldconfig should normally be run by the superuser as it may require write permission on some root owned directories and files.

Options

Verbose mode. Print current version number, the name of each directory as it is scanned, and any links that are created. Overrides quiet mode.

Only process directories specified on the command line. Don’t process the trusted directories (/lib and /usr/lib) nor those specified in /etc/ld.so.conf. Implies -N.

Don’t rebuild the cache. Unless -X is also specified, links are still updated.

Don’t update links. Unless -N is also specified, the cache is still rebuilt. -f conf Use conf instead of /etc/ld.so.conf. -C cache Use cache instead of /etc/ld.so.cache. -r root Change to and use root as the root directory. -l

Library mode. Manually link individual libraries. Intended for use by experts only.

Print the lists of directories and candidate libraries stored in the current cache.

Files

File containing a list of colon, space, tab, newline, or comma-separated directories in which to search for libraries.

Источник

Ldconfig самая полезная команда для новичков сборки в Linux

Рано или поздно любой из начинающих изучать Линукс сталкивается с такой задачей как сборка (компиляция) какого-либо пакета (программы) из исходных кодов (source code). Такая необходимость возникает довольно часто при обновлении программного продукта, либо его установки из CVS источников, либо вообще есть программные продукты которые не распространяются в package (rpm, deb) формате, а только в исходных кодах.

По сути дела задача довольно тривиальная и сводится, как правило, к набору команд ./configure; make; make install, да к тому-же весь процесс сборки и инсталяции подробно описывается в пояснительных файлах пакета, к примеру README, INSTALL, INSTALL-SOURCE, documentation, SOURCE и т.п., хотя это далеко не факт, что такие описания могут вообще присутствовать.

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

Все бы ничего, но, камнем преткновения при сборке становятся самые распространенные ошибки, звучащие к примеру так:

Все эти ошибки вызваны одним: Ваш сборщик объектных файлов не смог найти необходимых ему библиотек сопутствующих продуктов, необходимых для полной корректной сборки. Конечно, можно залезть в скрипт сборки и начать там ручками править пути к этим библиотекам, хотя за Вас это должен был сделать конфигуратор, но случается что и он то-же не панацея, вобщем это не наш путь, наша палочка-выручалочка утилита ldconfig, которая создает необходимые связки и формирует кэш динамических библиотек установленных в Вашем Линуксе.
Вам всего лишь необходимо отредактировать файл /etc/ld.so.config, в котором хранятся пути к необходимым библиотекам. К примеру, можно забить туда строки:

и выполнить с консоли команду ldconfig, после которой эта утилита просмотрит указанные ей директории на наличие там библиотек и поместит ссылки на них в кэш.
Просмотреть, какие-же библиотеки в данный момент находятся в кэше можно командой:

И в ответ Вы получите длиннющий список, а поэтому, для более удобной конкретики, чтобы посмотреть, есть ли у Вас библиотеки от пакета mysql, можно так:

Поначалу, в пору своей первобытности в Линуксе, сам неоднократно наступал на эти грабли, и мои друзья на них наступали, и друзья моих друзей получали эти шишки . и самое интересное, что пока, кроме Интернета, ни в одной книжке по Линукс я не встречал больших рекламных плакатов: «Изучите работу ldconfig. «, а стоило бы это кричать уже на первых страницах.

Короче, — берегите лоб, надеюсь я Вам помог в этом.

Источник

3 UNIX / Linux ldconfig Command Examples

What is ldconfig?

ldconfig is used to create, udpate and remove symbolic links for the current shared libraries based on the lib directories present in the /etc/ld.so.conf

3 ldconfig Examples

1. Display current libraries from the cache

This displays the list of directories and the libraries that are stored in the current cache. In the following example, it indicates that there are 916 libraries found in the cache file /etc/ld.so.cache, and it lists all of them below.

2. Display libraries from every directory

Scans all the directories, and prints the directory name, and all the links that are created under it.

The /etc/ld.so.conf has an include statement, which indicates that all the *.conf file under /etc/ld.so.conf.d directory should be considered.

As you see below, there are multiple *.conf file located under this ld.so.conf.d directory. All of these files will be used.

Sometimes when you do ldconfig -v, you might get the following error. This is because the directory referred by some of the *.conf file located under /etc/ld.so.conf.d is not valid, and contains directory names that doesn’t exist.

Note: You can either ignore these error mesages are remove those *.conf files from the /etc/ld.so.conf.d directory.

3. Inform System about the New Libraries

If you’ve installed a new program by compiling it from source, you might want to inform the system about the new libraries.

For example, let us assume that you’ve installed a program called dummy, which has all it’s libraries under /opt/dummy/lib directory.

Читайте также:  Windows tablets 10 inches

The following example will update the links using only the directory /opt/dummy/lib. This doesn’t rebuilt the links by processing the /etc/ld.so.conf file. Please note that this doesn’t rebuild the cache. It just updates the link.

Instead of the above, you can also add the “/opt/dummy/lib” to /etc/ld.so.conf and do the following.

Syntax and Options

Short Option Long Option Option Description
-v –verbose Indicates verbose mode. Prints current version number, name of each directory as it is scanned and links that are created.
-n Process the directories that are specified from the command line. This doesn’t process the regular /usr/lib and lib directories. This also doesn’t process directories specified in the /etc/ld.so.conf. This option implies -N.
-N This doesn’t rebuild the cache. Unless -X is also specified, links are still updated.
-X This doesn’t update the links. Unless -N is also specified, the cache is still rebuilt.
-f Use the specified config file instead of /etc/ld.so.conf.
-C Use the specified cache instead of /etc/ld.so.cache.
-r Change to and use root as the root directory.
-l This is library mode, which manually links individual libraries.
-p –print-cache Print the lists of directories and candidate libraries stored in the current cache.
-c FORMAT –format=FORMAT Uses FORMAT for the cache file. Valid values for FORMAT: old, new and compat. compat is the default value.
-i –ignore-aux-cache Ignore auxiliary cache file.
-? –help, –usage Display help
-V –version Display version number

Comments on this entry are closed.

Thanks for the tutorial.

I did the following

/vcp/SVN/Sofa-1.0/lib/linux$ ldconfig -l /media/DATA/VersionControlProjects/SVN/Sofa-1.0/lib/linux/*.*

and recieved this error message.
/sbin/ldconfig.real: Ignored file /media/DATA/VersionControlProjects/SVN/Sofa-1.0/lib/linux/libtinyxml.so since it is not a regular file.

vcp is a symbolic link from my linux drive to my /media/DATA drive.
What is a regular file and why are these “not regular” files being ignored?

One critical piece of information was left out of this article thus rendering it useless to anyone who doesn’t already know the info.

What goes in the *.conf files under the /etc/ld.so.conf/d/ directory?

@Steve: One line, containing the path to the folder you want to include in search for the matching .so.

Источник

Manage Libraries With ldconfig Command In Linux

Linux applications, tools, services uses libraries to get necessary functionalities. Libraries provides a lot of functionality to the related applications, tools and services. One library can be used by different applications. This is called dynamic library using or loading.

Shared Libraries

Shared libraries reside in /lib , /lib64 and /usr/lib . Each library is put into related directories like apt , gcc or similar. Dynamic libraries generally have extension .so but there are also some version related numbering.

For example libvte.so.9 is a dynamic library for vte which version is 9 .

Shared Libraries

Add Path To ldconfig

Some times the required libraries for the executable is not located in the standard paths. The default library path is hold in LD_LIBRARY_PATH environments variable. We should add new path to this variable. In the example we assume that the new library path is /foo

Add Path To ldconfig

Читайте также:  Sata режим для ssd windows 10

Rebuild Cache

ldconfig is located at /etc/ld.so.conf which content is like below. We will add the library path with include command. The final content will be like below.

Now we will run the ldconfig -p command to read configuration file and rebuild the cache.

Источник

ldconfig – команда Linux – команда Unix

Команда ldconfig Linux создает необходимые ссылки и кэш (для использования компоновщиком во время выполнения, ld.so ) с самыми последними общими библиотеками, найденными в каталогах, указанных в командной строки, в файле /etc/ld.so.conf и в доверенных каталогах (/usr/lib и /lib ).

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

ldconfig будет пытаться определить тип библиотек ELF (т. е. libc 5.x или libc 6.x (glibc)) на основе того, с какими библиотеками C, если они есть, были связаны библиотеки, поэтому при создании динамического библиотеках, имеет смысл явно ссылаться на libc (используйте -lc). ldconfig может хранить несколько типов библиотек ABI в одном кеше на архитектурах, которые допускают собственный запуск нескольких ABI, таких как ia32/ia64/x86_64 или sparc32/sparc64.

Некоторые существующие библиотеки не содержат достаточно информации, чтобы разрешить вывод их типа, поэтому формат файла /etc/ld.so.conf позволяет указать ожидаемый тип. Это только используется для тех ELF-библиотек, с которыми мы не можем разобраться. Формат выглядит так: «dirname = TYPE», где типом может быть libc4, libc5 или libc6. (Этот синтаксис также работает в командной строке). Пробелы не разрешены. Также см. Параметр -p .

Имена каталогов, содержащие = , больше не являются допустимыми, если у них также нет ожидаемого описателя типа.

ldconfig обычно должен запускаться суперпользователем, поскольку для этого может потребоваться разрешение на запись в некоторые корневые каталоги и файлы. Если вы используете параметр -r для изменения корневого каталога, вам не обязательно быть суперпользователем, если у вас достаточно прав на это дерево каталогов.

конспект

Опции

-v – подробный режим. Напечатайте номер текущей версии, имя каждого каталога во время его сканирования и любые созданные ссылки.

-n – только каталоги процессов, указанные в командной строке. Не обрабатывайте доверенные каталоги (/usr/lib и /lib ) и каталоги, указанные в /etc/ld.so.conf . Подразумевается -N .

-N . Не перестраивайте кеш. Если -X также не указано, ссылки по-прежнему обновляются.

-X – не обновлять ссылки. Если -N также не указано, кэш все еще перестраивается.

-f conf – используйте conf вместо /etc/ld.so.conf .

-C cache – используйте кеш вместо /etc/ld.so.cache .

-r root – перейдите в root и используйте его в качестве корневого каталога.

-l – режим библиотеки. Вручную связать отдельные библиотеки. Предназначено для использования только специалистами.

-p – используйте print-cache , чтобы распечатать списки каталогов и библиотек-кандидатов, хранящиеся в текущем кэше.

-cформат = FORMAT для файла кэша. Возможны варианты: старый, новый и совместимый (по умолчанию).

-?справка/использование для получения информации об использовании.

-Vверсия для версии для печати и выхода.

Примеры

установит правильные ссылки для общих двоичных файлов и перестроит кеш.

Пользователь root после установки новой общей библиотеки будет корректно обновлять символические ссылки общей библиотеки в/lib.

Смотрите также

ldd (1) – команда Idd в Linux для отображения общих библиотек, необходимых для любой конкретной программы.

Используйте команду man (% man ), чтобы увидеть, как команда используется на вашем конкретном компьютере.

Источник

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