Cannot load shared library linux

Ошибка 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.

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

sudo apt search libfuse2

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

sudo apt install libfuse2

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

sudo apt install libfuse-dev

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

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

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

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

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

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

Читайте также:  Operating system tool windows

Теперь мы знаем, что она находится по адресу /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, а также как ее решить. В большинстве случаев проблема решается довольно просто и вы получите работоспособную программу. Надеюсь, эта информация была полезной для вас.

Источник

[BUG] Unable to load shared library ‘libSkiaSharp’ or one of its dependencies in AWS Linux #964

Comments

KevinDJones commented Sep 24, 2019

Description

I built out a .NET Core 2.1 API that uses SkiaSharp. Works great on Windows & Mac. Deployed to AWS Amazon Linux 2 (Amazon’s custom version of CentOS). When I hit the endpoint, I get:

Unable to load shared library ‘libSkiaSharp’ or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: liblibSkiaSharp: cannot open shared object file: No such file or directory

I’ve already added SkiaSharp.NativeAssets.Linux to my project. I tried putting libSkiaSharp.so in my bin folder to no avail.

I took the error’s advice and enabled LD_DEBUG and found the following:

So I copied libSkiaSharp.so to /usr/lib64 and then it started working! But this isn’t ideal in my production environment, and I’d much rather it just look locally as opposed to deep in the system. Is there somewhere else I can put it without needing to access the AWS machine it’s running on?

The text was updated successfully, but these errors were encountered:

f2calv commented Oct 13, 2019

I have a similar issue with a .NET Core 3.0 deployment, it was working fine during preview releases of .NET Core 3 up-to preview 9, then seemingly when .NET Core 3.0 final was released it then failed with the same error as you.

Adding the following to my Dockerfile fixed the issue;

  • RUN apt-get update && apt-get install -y libfontconfig1

I guess the underlying image and its dependencies must have changed (regardless of having SkiaSharp.NativeAssets.Linux installed), so maybe this tweak will help.

mattleibow commented Nov 4, 2019

If you aren’t doing things with text, or if you are brining your own fonts, you could try
https://www.nuget.org/packages/SkiaSharp.NativeAssets.Linux.NoDependencies

This NuGet is the same as SkiaSharp.NativeAssets.Linux, but does not have the fontconfig dependency. The downside is that it doesn’t have the same support of features — mostly font finding. But it can still draw text.

eoware commented Aug 28, 2020

I built a lambda layer based on the instructions from this page, using my lambda project instead of the one in the post: https://www.leadtools.com/help/sdk/v20/tutorials/documents/cross-platform/dotnet-core/convert-documents-using-aws-lambda.html
This makes it so my lambda actually runs without exception — no more «Unable to load shared library ‘libSkiaSharp’ or one of its dependencies», but the output is what I am guessing is a default, just a small white square, not the output I get when I run the function locally in debug mode. My project basically just does some DrawText calls to a canvas.

Читайте также:  Как пропускать весь трафик через тор windows

For reference, the libraries the script adds for the layer are:
libbz2.so.1
libc.so.6
libdl.so.2
libexpat.so.1
libfontconfig.so.1
libfreetype.so.6
libm.so.6
libpng15.so.15
libpthread.so.0
libuuid.so.1
libz.so.1

matt-moody commented Sep 10, 2020

I have a similar issue with a .NET Core 3.0 deployment, it was working fine during preview releases of .NET Core 3 up-to preview 9, then seemingly when .NET Core 3.0 final was released it then failed with the same error as you.

Adding the following to my Dockerfile fixed the issue;

  • RUN apt-get update && apt-get install -y libfontconfig1

I guess the underlying image and its dependencies must have changed (regardless of having SkiaSharp.NativeAssets.Linux installed), so maybe this tweak will help.

@f2calv your solution worked for me! Thank you for posting this! I am running .net core 3.1 and was running into the OP above listed error during my cloud deployments to google app engine. During local development on my mac, I had zero issues so you can imagine I was quite perplexed by google app engine giving me grief over this. I tried every variation of the SkiaSharp, SkiaSharp.NativeAssets.Linux, SkaiSharp.NativeAssets.Linux.NoDependencies and every single one failed when deployed to the cloud (all worked while developing on my local machine). Once I flipped over to using a custom docker file and added the libfontconfig1 package, my cloud deployed code worked as expected.

Here’s how I solved this

For those who come after me, here is a snippet of nuget packages in my .csproj:

Источник

Linux — cannot load shared library «python36» and «kernel32.dll» #2

Comments

szmcdull commented Aug 21, 2019

Environment

  • Pythonnet version: Python.Runtime.NETStandard 3.6.1 from nuget
  • Python version: 3.6.8
  • Operating System: CentOS Linux release 7.6.1810 (Core)

Details

Describe what you were trying to get done.

What commands did you run to trigger this issue? If you can provide a
Minimal, Complete, and Verifiable example
this will help us understand the issue.

  • If there was a crash, please include the traceback here.

At first it could not find libpython36.so

and then it cannot find kernel32.dll now:

my program is build using the following command:

The text was updated successfully, but these errors were encountered:

szmcdull commented Aug 21, 2019

I read your blog and try to use Python.Included

It works in Windows. But not in Linux either.
My projects use .net core 3.0, not mono. Will this be supported?

henon commented Aug 21, 2019

if you are willing to work on it 😉 . seems like easy to solve for someone who has a linux box and wants it solved. I’ll release a linux nuget if you manage to get it working and send a PR.

henon commented Aug 21, 2019

I read your blog and try to use Python.Included

It works in Windows. But not in Linux either.
My projects use .net core 3.0, not mono. Will this be supported?

This is misplaced. it is not a pythonnet_netstandard problem, it is a Python.Included problem. Pythonnet_netstandard is available for linux: https://www.nuget.org/packages/Python.Runtime.Linux/
but Python.Included isn’t yet

szmcdull commented Aug 22, 2019

if you are willing to work on it 😉 . seems like easy to solve for someone who has a linux box and wants it solved. I’ll release a linux nuget if you manage to get it working and send a PR.

I wonder if we can put windows/linux/mac dists all in one nuget package. I’m looking into MS doc:

szmcdull commented Aug 22, 2019

I try to release a nuget package with the following folder structure:

with no luck. Project consuming the package cannot reference the Python.Runtime.dll inside it. Seems the runtime folder is only for native libraries. Maybe consider building one Python.Runtime.dll for all platforms, removing the #ifs.

Читайте также:  Plymouth ��� mint linux

szmcdull commented Aug 22, 2019 •

I confirm the Python.Runtime.Linux works under Linux without Mono. Now I can consume the nuget package using condition attributes:

When I debug in Visual Studio, RuntimeIdentifier is empty (‘$(RuntimeIdentifier)’ == »). When I publish the project to my server, I must specify the RuntimeIdentifier with the -r argument:

Maybe you can make Python.Runtime.NETStandard conditionally depend on Python.Runtime.Windows/Linux/OSX? I haven’t tried yet as I am happy with what I’ve tried by now.

henon commented Aug 22, 2019

Maybe you can make Python.Runtime.NETStandard conditionally depend on Python.Runtime.Windows/Linux/OSX? I haven’t tried yet as I am happy with what I’ve tried by now.

That would be a nice solution if possible. Not sure how to get that working though.

henon commented Aug 22, 2019

szmcdull commented Aug 23, 2019

That was only for testing. Not working yet.

szmcdull commented Aug 23, 2019

henon commented Aug 23, 2019

Cool, how did you create that nuget? Could you send a pull request?

szmcdull commented Aug 24, 2019

I just zip it manually

szmcdull commented Aug 24, 2019

Final folder structure:

The runtimes folder is used only in run-time and final publish. The ref folder is used in design-time so that the IDE and compiler would not complain about missing namespaces and classes.

dasMulli commented Sep 9, 2019

If there is a build process that can create all these files (variants of Python.Runtime.dll), i could help you set up a build that works with dotnet pack — as long as one platform can build these versions.
Previously used a manually compiled version from the master branch but now that i move xplat & docker, this nuget packge is super helpful.

henon commented Sep 9, 2019

great @dasMulli, I’d much appreciate if you would be able to extend my ReleaseBot see source code to create such a nuget as @szmcdull created manually. That will make sure that such a nuget will be available for all future updates to the library. If you need my help I’ll try to make some time.

dasMulli commented Sep 9, 2019

Looks fine, i’ll likely need to play with it for some time but it looks doable.
It should also be possible to merge mono and netstandard assemblies in one package with lib\osx-x64\net4\.. as well as netstandard.
If there is a canonical build slice that can be used as public API, the file in \ref could even be generated by roslyn through the

property.
Upside: could be a single package for both .NET Framework (netfx on win, mono on others) and .NET Standard for each version combo.
Downside: Restoring RID-specific content for .NET Framework applications is a bit of a mess.. NuGet gets its knowledge about RIDs form a «RID graph» that is distriuted via NuGet — if the package references Microsoft.NETCore.Platforms it works because the graph is in there. Only the latest previews of NuGet already contain this graph with the tooling, but i’m not sure if this is exclusive to the dotnet CLI. Worst case: TFM-specific dependency on this package for net* only.

henon commented Jul 31, 2020

@dasMulli I upgraded the release_bot to release pythonnet not only for netstandard2.0 but also for net40, all in one go. Also in order to easily rebase to newer pythonnet versions I completely cleaned up this repos commit history.

if you still want to improve upon the release_bot you’d be very welcome to do so, as the number of packages that arise from all combinations of compilation targets is exploding.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

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