Linux unable to load shared library

Linux error while loading shared libraries: cannot open shared object file: No such file or directory

Program is part of the Xenomai test suite, cross-compiled from Linux PC into Linux+Xenomai ARM toolchain.

# echo $LD_LIBRARY_PATH /lib # ls /lib ld-2.3.3.so libdl-2.3.3.so libpthread-0.10.so ld-linux.so.2 libdl.so.2 libpthread.so.0 libc-2.3.3.so libgcc_s.so libpthread_rt.so libc.so.6 libgcc_s.so.1 libstdc++.so.6 libcrypt-2.3.3.so libm-2.3.3.so libstdc++.so.6.0.9 libcrypt.so.1 libm.so.6 # ./clocktest ./clocktest: error while loading shared libraries: libpthread_rt.so.1: cannot open shared object file: No such file or directory 

This might happen if you have recently installed a shared library and didn’t run ldconfig(8) afterwards. Do ‘ldconfig’, there’s no harm in it.

+1 to @AbiusX comment — running sudo ldconfig (assuming that libraries are in fact where they should be [/usr/bin/lib/, /usr/bin/include/, /usr/local/lib/ and /usr/local/include/ AFAIK], please correct me if I’m wrong) can resolve that problem. Cheers!

Note that this error can also arise if the permissions on your lib file got changed somehow. Changing the permissions back to 644 solved it for me.

@AbiusX I ran sudo ldconfig after compiling my program and it worked. Thanks! (The libraries were in /usr/local/lib.)

19 Answers 19

Your library is a dynamic library. You need to tell the operating system where it can locate it at runtime.

To do so, we will need to do those easy steps:

    Find where the library is placed if you don’t know it.

sudo find / -name the_name_of_the_file.so 
LD_LIBRARY_PATH=/usr/local/lib 
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/my_library/ export LD_LIBRARY_PATH ./my_app 

The above mentioned answer was very clear, Thanks you first of all. I tried doing this in my Eclipse CDT Project Path (Lubuntu). /Debug$ echo $LD_LIBRARY_PATH /home/akhil/HDE/x86.linux/lib:/home/akhil/HDE/x86.linux/lib.. «/home/akhil/HDE/x86.linux/lib» this is where my libraries are actually available even, but still I get the same error. Any suggestions!

Try a «ldconfig» command after exporting your library. You might need to execute this command as «sudo».

I believe LD_LIBRARY_PATH should point to the directory containing path.so.something , not to path.so.something itself.

This is the right solution for the systems where sudo ldconfig cannot be executed, e.g. supercomputers.

The export LD_LIBRARY_PATH command is essential so that other programs can read the environment variable. Without it only the shell can see the variable.

Here are a few solutions you can try:

ldconfig

As AbiusX pointed out: If you have just now installed the library, you may simply need to run ldconfig.

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).

Usually your package manager will take care of this when you install a new library, but not always, and it won’t hurt to run ldconfig even if that is not your issue.

Читайте также:  Управление вентиляторами linux manjaro

Dev package or wrong version

If that doesn’t work, I would also check out Paul’s suggestion and look for a «-dev» version of the library. Many libraries are split into dev and non-dev packages. You can use this command to look for it:

This can also help if you simply have the wrong version of the library installed. Some libraries are published in different versions simultaneously, for example, Python.

Library location

If you are sure that the right package is installed, and ldconfig didn’t find it, it may just be in a nonstandard directory. By default, ldconfig looks in /lib , /usr/lib , and directories listed in /etc/ld.so.conf and $LD_LIBRARY_PATH . If your library is somewhere else, you can either add the directory on its own line in /etc/ld.so.conf , append the library’s path to $LD_LIBRARY_PATH , or move the library into /usr/lib . Then run ldconfig .

To find out where the library is, try this:

sudo find / -iname *libraryname*.so* 

(Replace libraryname with the name of your library)

If you go the $LD_LIBRARY_PATH route, you’ll want to put that into your ~/.bashrc file so it will run every time you log in:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/library 

By default, /lib and /usr/lib but not /usr/local/lib? That has thrown me off several times over my career and wasted hours.

Adding .conf files of my own with the non-standard lib paths I need to /etc/ld.so.conf.d (pointed to by /etc/ld.so.conf ) did the trick.

+1 for needing to run ldconfig. I wasn’t using a package manager. I had to compile from source, so this was necessary.

Just like @CivFan, I added my own .conf in /etc/ld.so.conf.d . After which I (obviously) had to run ldconfig and it worked. I can feel you @DarenW. Its a pain in the butt

Update
While what I write below is true as a general answer about shared libraries, I think the most frequent cause of these sorts of message is because you’ve installed a package, but not installed the -dev version of that package.

Well, it’s not lying — there is no libpthread_rt.so.1 in that listing. You probably need to re-configure and re-build it so that it depends on the library you have, or install whatever provides libpthread_rt.so.1 .

Generally, the numbers after the .so are version numbers, and you’ll often find that they are symlinks to each other, so if you have version 1.1 of libfoo.so, you’ll have a real file libfoo.so.1.0, and symlinks foo.so and foo.so.1 pointing to the libfoo.so.1.0. And if you install version 1.1 without removing the other one, you’ll have a libfoo.so.1.1, and libfoo.so.1 and libfoo.so will now point to the new one, but any code that requires that exact version can use the libfoo.so.1.0 file. Code that just relies on the version 1 API, but doesn’t care if it’s 1.0 or 1.1 will specify libfoo.so.1. As orip pointed out in the comments, this is explained well at here.

Читайте также:  Переименовать директорию linux терминал

In your case, you might get away with symlinking libpthread_rt.so.1 to libpthread_rt.so . No guarantees that it won’t break your code and eat your TV dinners, though.

Источник

Linux: executable cannot find shared library

I have compiled casablanca and have put -l:/~/path/to/lib/libcasablanca.so in my CMakeList.txt . I have build my application and I have got no errors. But when I run the executable it says:

./myproj: error while loading shared libraries: libcasablanca.so: cannot open shared object file: No such file or directory 

I have done it on another computer and it seems to work fine. Does anyone know what is the problem? How to fix this? I have no administrator access to this machine.

1 Answer 1

This is very simple: your library is not in the default system path from them the shared libraries are imported. During the compilation, the compile scripts solved these problems. In runtime, you have the LD_PRELOAD or LD_LIBRARY_PATH environment variables.

For example: an export LD_LIBRARY_PATH=/home/darkside/wunderprog/lib will extend the directoried searched for your libraries with the named directory. If there is your libcasablanca.so , you will get what you want.

Normally I use a /home//lib directory in my useronly accounts and set LD_LIBRARY_PATH from .profile .

If I do export LD_LIBRARY_PATH=/~/path/to/lib , does it removes the values existent in the variable? Or there is nothing in it?

@thedarksideofthemoon Yes, but normally it is empty (the system sharedlib search path isn’t there). If you have some important there, you can give him a colon-separated path list, just as we can see in $PATH : export LD_LIBRARY_PATH=/home/darkmoon/lib:/home/darkmoon/some_another/lib . or just so.

Источник

Ошибка error while loading shared libraries

Новые и опытные пользователи Linux могут сталкиваться с ошибкой error loading shared libraries во время запуска программ, также с ней могут сталкиваться программисты и все желающие компилировать программное обеспечение в своей системе. Эта ошибка в дословном переводе означает что возникла проблема во время загрузки общей библиотеки. О том что такое библиотеки и зачем они нужны вы можете узнать из статьи библиотеки Linux.

В этой же статье мы рассмотрим что значит ошибка error while loading shared libraries более подробно, а главное, как ее решить.

Что означает error while loading shared libraries?

Даже если вы не компилируете свои программы, то вы можете увидеть ошибку error while loading shared libraries: имя_библиотеки: cannot open shared object file: No such file or directory достаточно часто во время установки новых программ не через пакетный менеджер или программ, предназначенных для другого дистрибутива. Как я уже говорил, она возникает потому, что система не может найти библиотеку.

А вот почему ее нельзя найти и загрузить, это уже интересно. Этому может быть несколько причин:

  • Библиотека не установлена в системе;
  • Библиотека установлена, но неизвестно куда;
  • Библиотека установлена правильно, но имеет не ту версию.

При решении проблемы мы будем руководствоваться именно этими причинами и пытаться их решить.

Как исправить ошибку?

1. Библиотека не установлена

Первый вариант, тут все понятно, библиотеки просто нет в системе, поэтому мы и получаем такую ошибку. Верный способ ее решения — просто найти пакет библиотеки с помощью пакетного менеджера и установить ее. Обычно, пакеты с библиотеками называются так же, как и сами библиотеки с префиксом lib.

Читайте также:  Red hat linux fonts

Например, если нам не хватает библиотеки libfuse2.so, то мы можем найти ее в Ubuntu такой командой:

Затем осталось только установить ее:

sudo apt install libfuse2

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

sudo apt install libfuse-dev

И так для любой библиотеки. Но это не всегда помогает.

2. Библиотека находится не в том каталоге

Бывает что библиотека установлена, мы установили ее или она поставлялась вместе с программой, но ошибка как была, так и есть. Причиной этому может быть то, что загрузчик Linux не может найти библиотеку.

Поиск библиотек выполняется по всех папках, которые указаны в конфигурационных файлах /etc/ld.conf.d/. По умолчанию, это такие каталоги, как /usr/lib, /lib, /usr/lib64, /lib64. Если библиотека установлена в другой каталог, то, возможно, это и есть причина проблемы.

Вы можете посмотреть какие библиотеки сейчас доступны загрузчику с помощью команды:

Найти, где находится ваша библиотека можно с помощью команды locate. Например, нас интересует библиотека librtfreader.so:

Теперь мы знаем, что она находится по адресу /opt/kingsoft/wps-office/office6/. А значит, для работы программы необходимо сделать чтобы загрузчик библиотек ее видел. Для этого можно добавить путь в один из файлов /etc/ld.so.conf.d/ или же в переменную LD_LIBRARY_PATH:

Опять же, так вы можете поставить с любой библиотекой, которая взывает ошибку. Еще один более простой метод — это просто создать символическую ссылку на нужную библиотеку в правильной папке:

ln -s /opt/kingsoft/wps-office/office6/librtfreader.so /usr/lib/librtfreader.so

3. Неверная версия библиотеки

Эта причина ошибки довольно часто встречается при использовании программ не для вашего дистрибутива. Каждая библиотека имеет дополнительную версию, так называемую ревизию, которая записывается после расширения .so. Например, libav.so.1. Так вот, номер версии меняется всякий раз, когда в библиотеку вносятся какие-либо исправления.

Часто возникает ситуация, когда в одном дистрибутиве программа собирается с зависимостью от библиотеки, например, libc.so.1, а в другом есть только libc.so.2. Отличия в большинстве случаев здесь небольшие и программа могла бы работать на второй версии библиотеки. Поэтому мы можем просто создать символическую ссылку на нее.

Например, библиотеки libusb-1.0.so.1 нет. Но зато есть libusb-1.0.so.0.1, и мы можем ее использовать:

Для этого просто создаем символическую ссылку на библиотеку:

sudo ln -s /usr/lib/libusb-1.0.so.0.1 /usr/lib/libusb-1.0.so.1

В большинстве случаев программа не заметит подмены и будет работать, как и ожидалось. Также для решения этой проблемы можно попытаться найти нужную версию библиотеки в интернете для своей архитектуры и поместить ее в папку /usr/lib/ или /usr/lib64/. Но после этого желательно обновить кэш:

Выводы

В этой статье мы рассмотрели почему возникает ошибка Error while loading shared libraries, а также как ее решить. В большинстве случаев проблема решается довольно просто и вы получите работоспособную программу. Надеюсь, эта информация была полезной для вас.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

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