Новые и опытные пользователи Linux могут сталкиваться с ошибкой error loading shared libraries во время запуска программ, также с ней могут сталкиваться программисты и все желающие компилировать программное обеспечение в своей системе. Эта ошибка в дословном переводе означает что возникла проблема во время загрузки общей библиотеки. О том что такое библиотеки и зачем они нужны вы можете узнать из статьи библиотеки Linux.
В этой же статье мы рассмотрим что значит ошибка 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. Если библиотека установлена в другой каталог, то, возможно, это и есть причина проблемы.
Вы можете посмотреть какие библиотеки сейчас доступны загрузчику с помощью команды:
ldconfig -p
Найти, где находится ваша библиотека можно с помощью команды locate. Например, нас интересует библиотека librtfreader.so:
locate librtfreader
Теперь мы знаем, что она находится по адресу /opt/kingsoft/wps-office/office6/. А значит, для работы программы необходимо сделать чтобы загрузчик библиотек ее видел. Для этого можно добавить путь в один из файлов /etc/ld.so.conf.d/ или же в переменную LD_LIBRARY_PATH:
export LD_LIBRARY_PATH=/opt/kingsoft/wps-office/office6/
Опять же, так вы можете поставить с любой библиотекой, которая взывает ошибку. Еще один более простой метод — это просто создать символическую ссылку на нужную библиотеку в правильной папке:
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/. Но после этого желательно обновить кэш:
sudo ldconfig
Выводы
В этой статье мы рассмотрели почему возникает ошибка Error while loading shared libraries, а также как ее решить. В большинстве случаев проблема решается довольно просто и вы получите работоспособную программу. Надеюсь, эта информация была полезной для вас.
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .
When run a demo program (compiled in dos) in MINGW64, an error happens as follows
$ ./ResRdDemo.exe test.rst
«C:/users/user/desktop/bao/appwin/build/ResRdDemo.exe: error while loading shared libraries: ?: cannot open shared object file: No such file or directory.»
But it runs well in dos windows.
In addition, I compile a small program in MINGW64 and the compiled small program can run in MINGW64. But it can not in windows dos.
In summary, the program compiled in windows dos can not run in mingw64. the program compiled in mingw64 can not run in windows dos neither. any helps are appreciated.
Song
Check the PATH environment variable. The required shared libraries shall be on the same directory as the executable or on one of the directories listed on that variable.
Hello Alex,
Thanks for your response.
1.the dll file is in the same directory as the running program.
2.I edit my mingw64’s profile.local and add dll path. dll path is echoed.
3.the same error happens.
4.then I try it in msys instead of msys2 and use my another profile.local for msys. it works well.
5.I compare and contrast a few small programs in window dos, msys(old version) and msys2(new version include mingw64): the programs compiled in dos can run in old version msys and vice versa, but can not run in msys2 (mingw64). the programs compiled in mingw64 (in msys2) can run only in its command window.
6.Did I do something wrong for msys2 setting? But I follow msys2 installation instruction. What should I check?
7.In addition, I want to know where I can edit mingw64 environment variable PATH (or profile) so that PATH can be saved for next use.
Any helps are appreciated.
Song
an invalueable tool to see whats missing is some kind of dependency checker, msys2 has ntldd which is console only, if you strive for something a bit more visual use the dependencies tool from lucasg which supports win10 as well which the old depends.exe does not. Look for dll’s with question marks and you will have your answer.
How depends.exe fails on Windows 10? It works for me.
@songqingshan : make sure that you are don’t have around dlls compiled with different compilers/runtimes. To start, mixing MSYS/mingw32 and MSYS2/mingw-w64 binaries on the same system is asking for problems.
Then, as you probably know, if your executable depends on library A.DLL, this library may depend on other dlls, which must be reachable by the Windows rules. See https://msdn.microsoft.com/en-us/library/7d83bc18.aspx
It does not fail as such, but it does not support the new api load mechanism win10 uses, also its extremely slow to load on windows 10.
Hello Ralph,
I use windows 8.1 instead of windows 10.
two pieces of short code are attached for your try.
Regards,
Song
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: October 25, 2018 8:57 AM
To: Alexpux/MINGW-packages
Cc: songqingshan; Mention
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
It does not fail as such, but it does not support the new api load mechanism win10 uses, also its extremely slow to load on windows 10.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-433061386>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBU1K5njPgc1KjENECNEd_cbEs_F2yks5uocNIgaJpZM4X4db7>.
/*
* Since: 2.40. msys’s glib version 2.38. can not be compiled with msys
gcc `pkg-config —cflags —libs glib-2.0 dbus-glib-1` spawn.c -lglib-2.0.dll -lglib-2.0 -lgio-2.0 -lgio-2.0.dll
gcc `pkg-config —cflags —libs glib-2.0 dbus-glib-1` spawn.c -lglib-2.0.dll -lglib-2.0 -lgio-2.0 -lgio-2.0.dll -o spawn.exe
Compile me with:
gcc -o spawn spawn.c $(pkg-config —cflags —libs gtk+-3.0)
excuting results in MINGW64:
situation 1:
User@shan MINGW64 /c/users/user/desktop/gtkapp/thread-g-msys2-3/src
$ ./spawn.exe
(spawn.exe:217612): GLib-GIO-CRITICAL **: 09:56:53.957: g_subprocess_get_identifier: assertion ‘G_IS_SUBPROCESS (subprocess)’ failed
child_process id = (NULL)
Segmentation fault
User@shan MINGW64 /c/users/user/desktop/gtkapp/thread-g-msys2-3/src
situation 2:
User@shan MINGW64 /c/users/user/desktop/gtkapp/thread-g-msys2-3/src
$ ./spawn.exe
child_process id = 193508
end…
Normal message no: 0.
Normal message no: 1.
Normal message no: 2.
Normal message no: 3.
Normal message no: 4.
Normal message no: 5.
Normal message no: 6.
Normal message no: 7.
Normal message no: 8.
Normal message no: 9.
helper end …
Error message no: 0.
Error message no: 1.
Error message no: 2.
Error message no: 3.
Error message no: 4.
Error message no: 5.
Error message no: 6.
Error message no: 7.
Error message no: 8.
Error message no: 9.
User@shan MINGW64 /c/users/user/desktop/gtkapp/thread-g-msys2-3/src
error in msys2:
User@shan MSYS /c/users/user/desktop/gtkapp/thread-g-msys2-3/src
$ ./spawn
C:/users/user/desktop/gtkapp/thread-g-msys2-3/src/spawn.exe: error while loading shared libraries: ?: cannot open shared object file: No such file or directory
User@shan MSYS /c/users/user/desktop/gtkapp/thread-g-msys2-3/src
error in dos
«the procedure entry point g_subprocess_get_identifier could not be localted in the dynamic link libaray.»
*/
//#include <gtk/gtk.h>
#include <gio/gio.h>
#include <glib.h>
static void show_reslut()
{
g_print(«show_reslutn»);
}
static void store_result_cb (GObject *source_object, GAsyncResult *result, gpointer user_data)
{
GAsyncResult **p = user_data;
g_assert_nonnull (p);
g_assert_null (*p);
*p = g_object_ref (result);
g_print(«store_result_cb n»);
}
static void wait_for_result (GAsyncResult **result)
{
while (*result == NULL)
{
g_print(«whilen»);
g_main_context_iteration (NULL, TRUE);
g_print(«waitn»);
}
g_print(«returnn»);
}
int main( int argc, char **argv )
{
g_autoptr (GError) error = NULL;
g_autoptr (GSubprocess) subprocess = NULL;
g_autoptr (GAsyncResult) result = NULL;
g_autofree gchar *first_id = NULL;
g_autofree gchar *second_id = NULL;
//const gchar *example_requester;
//example_requester = g_test_get_filename (G_TEST_BUILT, «example-requester», NULL);
gint count=0;
do {
subprocess = g_subprocess_new (G_SUBPROCESS_FLAGS_STDOUT_PIPE, &error, «./helper», NULL);
count++;
}while(subprocess == NULL && count<=100);
g_print(«count = %dn», count);
return( 0 );
}
/*
* Compile me with:
* gcc -o helper helper.c
*/
#include <stdio.h>
#include <unistd.h>
int
main( int argc,
char **argv )
{
int i;
int num1=0;
int num2=0;
for( i = 0; i < 10; i++ )
{
char stdout_string[] = «Normal message no: .»;
char stderr_string[] = «Error message no: .»;
stdout_string[19] = ‘0’ + i;
stderr_string[18] = ‘0’ + i;
sleep( 1 );
num1 = fprintf( stdout, «%sn», stdout_string );
printf( «num1 = %dn», num1);
fflush(stdout);
sleep( 1 );
num2 = fprintf( stderr, «%sn», stderr_string );
printf( «num2 = %dn», num2);
fflush(stderr);
}
return( 0 );
}
Ill try later tonight, though these functions might have changed in later versions because of instability.
Atleast gtk works fine here with gimp-2.10.6 but specific use cases might allways break stuff.
P.s you say msys’s glib version, are we talking about Msys2 or MinGW64 compiles ?.
Hello,
I believe that you are on the point which is what I am going to say to you.
I try another independent test:
1.A dll is compiled with another compiler and I dump function’s names in the dll from its relevant tool.
2.Change dumped function’s names into appropriate names (e.g., to small case and append a underscore) which are needed by gcc gfortran compiler and create a .def file.
3.create a static library .a using the created .def file.
4.compile a small piece of code against the static library using gfortran.
5.run the created program.
6.the same runtime happens. In the error message, only a new function name replaces old function name.
7.above 1 to 6 explains what you said «don’t have around dlls compiled with different compilers/runtimes».
However, when I compile my test code (like spawn.c and help.c) in msys2 mingw64, I have not used other dll files except for build-in gtk libraries in msys2 mingw64. According to 1-6 and 8, I personally think the error is caused by the symbols of the gtk libraries in msys2 mingw64. In other words, the symbols are not compatible in windows dos. Therefore, some programs compiled in msys2 mingw64 can not be activated in windows dos commands. This is for your reference only.
Regards,
Song
…
Hello,
msys2 does not have ntldd. I search all subdirectories. I can not find it. I think that error is caused by build-in gtk in Msys2 mingw64.
Song
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: October 25, 2018 4:39 AM
To: Alexpux/MINGW-packages
Cc: songqingshan; Author
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
an invalueable tool to see whats missing is some kind of dependency checker, msys2 has ntldd which is console only, if you strive for something a bit more visual use the dependencies tool from lucasg which supports win10 as well which the old depends.exe does not. Look for dll’s with question marks and you will have your answer.
—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-432984406>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBU20Zi9IhhJHZI9ui4K3Kv3k4fjbfks5uoYbZgaJpZM4X4db7>.
Hello,
I have not installed MSYS2/mingw32.
As you see, I have not used other libraries except for built-in gtk libraries in msys2 mingw64.
Please do not mix msys and msys2. msys works fine for me. The reason I am going to change from msys to msys2 is gtk version. msys does not have a new gtk version which I need.
I think that if the programs compiled in MSYS2/MINGW64 does not work in windows dos, MSYS2/MINGW64 does not reach its goal.
Regards,
Song
…
Do you per chance have anything using gtk or dependent libraries installed on your PC/LapTop ?
A good way to find out is using Depends.exe if you use win 8.1 it should work ok.
Set it to show full paths and notice if any dll is located outside Msys2 dir.
If any are they most likely will interfere with your programs execution.
ntldd seems to have no package, get it from this repo, its located in the folder mingw-w64-ntldd-git
after getting the git repo cd to that folder in an msys2 shell and do makepkg-mingw -c -i —skippgp —nocheck and wait untill its done building and installing, then do ntldd with the full path to the program you want to check, remember if using the msys2 shell that paths need forward slashes eg. c:/someprogram.exe or /c/someprogram.exe
example on codeblocks.exe
ntldd c:/msys64/codeblocks.exe
COMCTL32.DLL => C:WindowsWinSxSx86_microsoft.windows.common-controls_6595b64144ccf1df_5.82.17134.345_none_40ff7c964511edcfCOMCTL32.DLL (0x00760000)
KERNEL32.dll => C:WindowsSYSTEM32KERNEL32.dll (0x01080000)
msvcrt.dll => C:WindowsSYSTEM32msvcrt.dll (0x01080000)
SHELL32.dll => C:WindowsSYSTEM32SHELL32.dll (0x01470000)
SHFOLDER.DLL => C:WindowsSYSTEM32SHFOLDER.DLL (0x00020000)
USER32.dll => C:WindowsSYSTEM32USER32.dll (0x010d0000)
exchndl.dll => c:msys64exchndl.dll (0x00020000)
wxmsw28u_gcc_cb.dll => c:msys64wxmsw28u_gcc_cb.dll (0x01470000)
codeblocks.dll => c:msys64codeblocks.dll (0x01470000)
wxpropgrid.dll => c:msys64wxpropgrid.dll (0x01080000)
1.
how can I «notice if any dll is located outside Msys2 dir»
2. Can you show me how I can get ntldd step by step?
in MINGW-package/mingw-w64-ntldd-git/, only PKGBUILD exists.
currently I can not get ntldd.
Song
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: October 25, 2018 1:19 PM
To: Alexpux/MINGW-packages
Cc: songqingshan; Mention
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
Do you per chance have anything using gtk or dependent libraries installed on your PC/LapTop ?
A good way to find out is using Depends.exe if you use win 8.1 it should work ok.
Set it to show full paths and notice if any dll is located outside Msys2 dir.
If any are they most likely will interfere with your programs execution.
ntldd seems to have no package, get it from this repo, its located in the folder mingw-w64-ntldd-git
after getting the git repo cd to that folder in an msys2 shell and do makepkg-mingw -c -i —skippgp —nocheck and wait untill its done building and installing, then do ntldd with the full path to the program you want to check, remember if using the msys2 shell that paths need forward slashes eg. c:/someprogram.exe or /c/someprogram.exe
example on codeblocks.exe
ntldd c:/msys64/codeblocks.exe
COMCTL32.DLL => C:WindowsWinSxSx86_microsoft.windows.common-controls_6595b64144ccf1df_5.82.17134.345_none_40ff7c964511edcfCOMCTL32.DLL (0x00760000)
KERNEL32.dll => C:WindowsSYSTEM32KERNEL32.dll (0x01080000)
msvcrt.dll => C:WindowsSYSTEM32msvcrt.dll (0x01080000)
SHELL32.dll => C:WindowsSYSTEM32SHELL32.dll (0x01470000)
SHFOLDER.DLL => C:WindowsSYSTEM32SHFOLDER.DLL (0x00020000)
USER32.dll => C:WindowsSYSTEM32USER32.dll (0x010d0000)
exchndl.dll => c:msys64exchndl.dll (0x00020000)
wxmsw28u_gcc_cb.dll => c:msys64wxmsw28u_gcc_cb.dll (0x01470000)
codeblocks.dll => c:msys64codeblocks.dll (0x01470000)
wxpropgrid.dll => c:msys64wxpropgrid.dll (0x01080000)
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-433154413>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBU3dfAS8ADgYpwkfV-4YsdqAyDBo1ks5uogCZgaJpZM4X4db7>.
see my example and notice the paths :), ofc dlls like C:WindowsSYSTEM32KERNEL32.dll are ok since its a windows system dll but if you see for example c:msys64codeblocks.dll in a place other than where you currently have codeblocks, then you have a problem cause it would pick that one up and it might not be the same version. In old days this is what we called dll hell because back then most dll’s where not versioned so easily got mixed up causing system crashes and all sorts of nasty instability.
as for building ntdll, you need to install msys2 since we use a package manager to build things.
when done that open msys2_shell.cmd and in the shell window change directory to the folder mingw-w64-ntdll-git.
not write this makepkg-mingw -c -i —skippgp —nocheck and it will build and install ntdll.
cant remember if the installer sets up shortcuts for mingw32 / mingw64 shells but if it does, open one of these and write ntldd path to the executable or dll you want to check. Example ntldd C:/something/somedll.dll and it will spit out a list like my example.
Examine that and notice if any dll’s are out of place, if they are then you need to take care of that by either temporarily removing those dll’s (just copy them somewhere else) or uninstalling the program using them if you no longer need it.
After that test if your own program works, if it does then we found the culprit,
if it does not then we have a real bug and we need to fix that :).
P.s remember to copy back the dll’s you moved after testing.
Im not the best to explain these things, so if its to hard to follow, i have ntldd prebuilt and can upload the packages if needed.
Why not use ldd
instead of ntldd
? ldd
comes with msys2 by default.
i seem to remember ldd having problems with windows dll’s but i might be wrong ?, if i am by all means use it its easier than the other thing.
Hello Ralph,
Your explanation is so good. I so appreciate your work and explanation.
A progress is made.
I have used depends, ntldd and ldd. Depends identify one of culprits as you said «dll hell». Although while compiling, the libraries of msys2 mingw 64 are specified, the program steals three libraries from msys mingw64. After disabling msys mingw64, the programs compiled in msys2 mingw64 can run in window dos, msys (after enabling it) and msys2 mingw64.
However, there is one issue that remains: the program compiled with intel fortran compiler (ifort) can run in windows dos, and msys, but can not run in msys2 and msys2 mingw64 command windows. I use depends to identify the issues as well. it seems that issues are related to three: API-MS-WIN-CORE-KERNEL32-PRIVATE-L1-1-1.DLL, API-MS-WIN-CORE-PRIVATEPROFILE-L1-1-1.DLL and API-MS-WIN-SERVICE-PRIVATE-L1-1-1.DLL. I want to know who (windows or mingw64) provides these files. I can send you two *.dwi files (static and dynamic) if you want.
Error is as follows:
User@shan MINGW64 /c/users/user/desktop/bao/appwin/build
$ ./ResRdDemo.exe test.rst
C:/users/user/desktop/bao/appwin/build/ResRdDemo.exe: error while loading shared libraries: ?: cannot open shared object file: No such file or directory
User@shan MINGW64 /c/users/user/desktop/bao/appwin/build
Thank your work once again,
Song
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: October 27, 2018 12:10 AM
To: Alexpux/MINGW-packages
Cc: songqingshan; Mention
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
see my example and notice the paths :), ofc dlls like C:WindowsSYSTEM32KERNEL32.dll are ok since its a windows system dll but if you see for example c:msys64codeblocks.dll in a place other than where you currently have codeblocks, then you have a problem cause it would pick that one up and it might not be the same version. In old days this is what we called dll hell because back then most dll’s where not versioned so easily got mixed up causing system crashes and all sorts of nasty instability.
as for building ntdll, you need to install msys2 since we use a package manager to build things.
when done that open msys2_shell.cmd and in the shell window change directory to the folder mingw-w64-ntdll-git.
not write this makepkg-mingw -c -i —skippgp —nocheck and it will build and install ntdll.
cant remember if the installer sets up shortcuts for mingw32 / mingw64 shells but if it does, open one of these and write ntldd path to the executable or dll you want to check. Example ntldd C:/something/somedll.dll and it will spit out a list like my example.
Examine that and notice if any dll’s are out of place, if they are then you need to take care of that by either temporarily removing those dll’s (just copy them somewhere else) or uninstalling the program using them if you no longer need it.
After that test if your own program works, if it does then we found the culprit,
if it does not then we have a real bug and we need to fix that :).
P.s remember to copy back the dll’s you moved after testing.
Im not the best to explain these things, so if its to hard to follow, i have ntldd prebuilt and can upload the packages if needed.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-433591706>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBU1orG0CqSNrtr6rZ7acfxrGYSIRaks5uo-rVgaJpZM4X4db7>.
sounds like api incompatibility, msys2 mingw64 uses the latest crt and headers for mingw64, and they shifted focus to ucrt (microsofts universal C runtime) this is a windows 10 feature and unfortunatly incompatible with any program compiled with older api. You will probably have to recompile everything you need in msys2 to get around that one, sorry to be the bearer of bad news :/.
Oh and btw those dlls are part of ucrt so definatly something to take into account.
In essence all microsoft dll’s starting with API- are part of the universal C runtime.
And Thanks
I wish that I can compile the subprogram in msys2 mingw64. But I can not because it imports a library which is compiled using ifort. I do not have the library code and I can not compile it even if I have.
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: October 27, 2018 12:15 PM
To: Alexpux/MINGW-packages
Cc: songqingshan; Mention
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
sounds like api incompatibility, msys2 mingw64 uses the latest crt and headers for mingw64, and they shifted focus to ucrt (microsofts universal C runtime) this is a windows 10 feature and unfortunatly incompatible with any program compiled with older api. You will probably have to recompile everything you need in msys2 to get around that one, sorry to be the bearer of bad news :/.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-433638555>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBU6SQvjB-EPwh52u4ZZ3r_O2PQeumks5upJShgaJpZM4X4db7>.
if it utililizes a dll you could probably make an import library and use the exports from that to link to your own code, but and thats a big but. You need the headers that came with that program, and if built using non gnu compilers you might have to modify a few things in those headers to make them compliant with gcc / gfortran. Also the code might not be happy with a bash shell, not all windows programs like this.
If you dont mind sharing the code ? i might be able to come up with something.
Hello Ralph,
1.
the program runs well in msys/mingw64 command window, but it cannot run in msys2/mingw64 command window. That is what you need to think about.
2.
I did what you said «make an import library and use the exports from that to link to your own code…» before we start our talk. I use gfortran to compile it. But during run time, it cannot link to the functions in the exported library. As you said, I have modified some things in the header. I tried a few ways. the outcome is the same: it cannot link to the functions in the lib. I am going to try a new means.
3.
I agree that «the code might not be happy with a bash shell», but again it runs well in msys/mingw64.
4.
I do not mind to share my own code. But this is a library and its demo from another company. It is the company’s proprietary product which can not be copied. However, if you really have interest, you can download it subject to some terms. thanks
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: October 28, 2018 12:57 AM
To: Alexpux/MINGW-packages
Cc: songqingshan; Mention
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
if it utililizes a dll you could probably make an import library and use the exports from that to link to your own code, but and thats a big but. You need the headers that came with that program, and if built using non gnu compilers you might have to modify a few things in those headers to make them compliant with gcc / gfortran. Also the code might not be happy with a bash shell, not all windows programs like this.
If you dont mind sharing the code ? i might be able to come up with something.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-433678882>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBU2sEgERC3Bj4_gicnQp81PfugsU1ks5upUdQgaJpZM4X4db7>.
Msys and Msys2 are two very different beasts Msys uses code to get around mapping unix paths to windows paths in a totally different way, Msys2 is closer to Cygwin in that regard eg. needs cygpath for certain otherwise hard to compile stuff, If you remove fstab from /etc you even get /cygdrive back, Msys does not have this option it maps to root by default.
Can you post a log about the linker errors ? it might give me some idea about whats going on.
I know that Msys and Msys2 are two very different beasts before I download msys2. The purpose of comparing and contracting Msys2 against Msys reminds you of mapping unix paths which maybe is a culprit (but I am not sure). Msys2 command window should run the programs compiled by other compilers like Msys command window. In addition, I have not excluded the interfere of Msys. However, I have renamed Msys in the C drive although I have removed it.
What does «post a log about the linker errors» mean? it means the output in msys2/mingw64 window as follows
»
$ ./ResRdDemo test.rst
C:/users/user/desktop/bao/appwin/build/ResRdDemo.exe: error while loading shared libraries: ?: cannot open shared object file: No such file or directory
»
or dwi files from depends? or other log files?
I believe more information can give you some idea about what’s going on.
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: October 28, 2018 11:50 AM
To: Alexpux/MINGW-packages
Cc: songqingshan; Mention
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
Msys and Msys2 are two very different beasts Msys uses code to get around mapping unix paths to windows paths in a totally different way, Msys2 is closer to Cygwin in that regard eg. needs cygpath for certain otherwise hard to compile stuff, If you remove fstab from /etc you even get /cygdrive back, Msys does not have this option it maps to root by default.
Can you post a log about the linker errors ? it might give me some idea about whats going on.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-433721861>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBU_JMBWobGXHoyrDrBRqD5PFCdliAks5upeA4gaJpZM4X4db7>.
$ ./ResRdDemo test.rst C:/users/user/desktop/bao/appwin/build/ResRdDemo.exe: error while loading shared libraries: ?: cannot open shared object file: No such file or directory
like that aye, just a bit more of it so that i can see where it looks for the dll.
Whats unclear to me is if its a dependency of the dll your trying to link to or the dll itself it cannot find, one sure way is putting a copy of the dll your trying to link to in C:WindowsSystem32 and then try building it again, if it fails with the same error then its most likely a dependency of that dll that it complains about, and we then need to find out which.
$ ldd ResRdDemo test.rst
ResRdDemo:
ntdll.dll => /c/Windows/SYSTEM32/ntdll.dll (0x7ff81aa10000)
KERNEL32.DLL => /c/Windows/system32/KERNEL32.DLL (0x7ff819a50000)
KERNELBASE.dll => /c/Windows/system32/KERNELBASE.dll (0x7ff817e40000)
binlib.dll => /c/users/user/desktop/bao/appwin/build/binlib.dll (0x7ff80f0b0000)
imagehlp.dll => /c/Windows/system32/imagehlp.dll (0x7ff81a700000)
MSVCR110.dll => /c/Windows/SYSTEM32/MSVCR110.dll (0x7ff80eee0000)
test.rst:
ldd: test.rst: Exec format error
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: October 29, 2018 1:48 AM
To: Alexpux/MINGW-packages
Cc: songqingshan; Mention
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
$ ./ResRdDemo test.rst C:/users/user/desktop/bao/appwin/build/ResRdDemo.exe: error while loading shared libraries: ?: cannot open shared object file: No such file or directory
like that aye, just a bit more of it so that i can see where it looks for the dll.
Whats unclear to me is if its a dependency of the dll your trying to link to or the dll itself it cannot find, one sure way is putting a copy of the dll your trying to link to in C:WindowsSystem32 and then try building it again, if it fails with the same error then its most likely a dependency of that dll that it complains about, and we then need to find out which.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-433804414>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBU6Tg2qpeH2oAMBNFlwQz5gB-taltks5upqSigaJpZM4X4db7>.
note: test.rst is in current directory.
$ ntldd ResRdDemo test.rst
ResRdDemo:
binlib.dll (0x00000000003c0000)
KERNEL32.dll => C:WindowsSYSTEM32KERNEL32.dll (0x0000000000720000)
imagehlp.dll => C:WindowsSYSTEM32imagehlp.dll (0x00000000003c0000)
test.rst:
test.rst: not found
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: October 29, 2018 1:48 AM
To: Alexpux/MINGW-packages
Cc: songqingshan; Mention
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
$ ./ResRdDemo test.rst C:/users/user/desktop/bao/appwin/build/ResRdDemo.exe: error while loading shared libraries: ?: cannot open shared object file: No such file or directory
like that aye, just a bit more of it so that i can see where it looks for the dll.
Whats unclear to me is if its a dependency of the dll your trying to link to or the dll itself it cannot find, one sure way is putting a copy of the dll your trying to link to in C:WindowsSystem32 and then try building it again, if it fails with the same error then its most likely a dependency of that dll that it complains about, and we then need to find out which.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-433804414>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBU6Tg2qpeH2oAMBNFlwQz5gB-taltks5upqSigaJpZM4X4db7>.
Sounds like test.rst is in a format your current windows does not support, is it by chance a 16 bit dos format one ?. in that case it will be impossible to load unless you have a 32 bit windows, 64 bit windows does not support 8 and 16 bit format anymore.
You might have luck with a virtual machine like windows 7’s XP mode.
Try dragging it inside the dependencies window, if it cannot load the symbols then its most likely we have a real DOS format executable on hand.
If not then it might be in OMF format which went out of style years back, but atleast then we can convert it to COFF.
Wait a second… rst is a restructured text file (ANSYS), you cannot link to it like you would a normal dll.
rst’s are also used by python doctools like sphinx for api documentation.
So its python we need to link to :),
that should be easy, export LIBS+=» -lpython2.7″ and make.
Then your test should work.
Sounds like unreasonable. test.rst is a binary file which is read well by ResRdDemo in Windows/dos and Msys/Mingw64 except for Msys2/mingw64. I believe that either Msys2/mingw64’s setting or Msys2/ming64 itself causes an issue.
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: November 1, 2018 4:40 AM
To: Alexpux/MINGW-packages
Cc: songqingshan; Mention
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
Sounds like test.rst is in a format your current windows does not support, is it by chance a 16 bit dos format one ?. in that case it will be impossible to load unless you have a 32 bit windows, 64 bit windows does not support 8 and 16 bit format anymore.
You might have luck with a virtual machine like windows 7’s XP mode.
Try dragging it inside the dependencies window, if it cannot load the symbols then its most likely we have a real DOS format executable on hand.
If not then it might be in OMF format which went out of style years back, but atleast then we can convert it to COFF.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-434986482>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBU8vu5PRfT4Yyqa7qewcHntNfmzXkks5uqsGTgaJpZM4X4db7>.
you can use ls in cmd ?, did you export msysbin to PATH ? atleast that might explain some things.
well i noticed the rst extension and according to what i could find its a python docutils file, but it would not be the first time people have used extensions for other things. But just for curiosity try open it with notepad :), if its readable then its text, if it shows garbadge characters then its most likely as you say a binary. As for having ls avaliable in cmd, if msysbin was exported to PATH it would interfere with msys2 possibly breaking certain functions like the ability to correctly run this.
I install both Msys/mingw64 and Msys2/mingw64 in C drive:
C:MinGW (Msys/mingw64)
C:msys64 (Msys2/mingw64)
In Msys, path is
$ echo $PATH
echo $PATH
.:/local32/bin:/mingw32/bin:/mingw/bin:/bin:/opt/bin:/opt/python3:/MinGW/msys/1.0/local/bin
However, when I use Msys/mingw64 commands console, I use my profile.local to set environment variable and path is as follows:
$ echo $PATH
.:/local64/bin:/mingw64/bin:/mingw/bin:/bin:/opt/bin:/opt/python3:C:Program Files (x86)Common FilesIntelShared Librariesredistintel64_wincompiler
in Msys2/mingw64,
$ echo $PATH
/mingw64/bin:/usr/local/bin:/usr/bin:/bin:/c/Windows/System32:/c/Windows:/c/Windows/System32/Wbem:/c/Windows/System32/WindowsPowerShell/v1.0/:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl
However, when I use Msys2/mingw64 console, I have to change «C:MinGW» into «C:MinGW-bak». Otherwise, «Msys2/mingw64» console searches for library files in «C:MinGW».
In windows system, path is as follows.
C:Program Files (x86)IntelSWToolscompilers_and_libraries_2018.5.274windowsmpiintel64bin;%INTEL_DEV_REDIST%redistintel64_winmpirt;%INTEL_DEV_REDIST%redistia32_winmpirt;%INTEL_DEV_REDIST%redistintel64_wincompiler;%INTEL_DEV_REDIST%redistia32_wincompiler;%SystemRoot%;%SystemRoot%system32;%SystemRoot%System32Wbem;%SYSTEMROOT%System32WindowsPowerShellv1.0;C:Python37;C:Python37Scripts;C:MinGWmsys1.0bin;C:MinGWmingw32bin;C:MinGWmingw64bin;C:MinGWmingw64shareaclocal;C:MinGWmingw64includelibxml2libxml;C:MinGWmsys1.0localbin;C:MinGWmingw64localbin;C:MinGWmingw64optbin;C:MinGWmingw64optusrbin;C:MinGWmingw32optlibpython2.7config;C:Program FilesANSYS IncANSYS Studentv190ansysbinwinx64;C:ANSYSv190ansysbinwinx64;C:ANSYSv190CFXtoolsicemcfd-19.0winx64IcemExe2CfxC:ANSYSv190TurboGridtoolsicemcfd-19.0winx64IcemExe2Cfx;C:UsersUserDesktopbaoansysbinlib;C:Program FilesMicrosoft SQL Server130ToolsBinn;C:msys64mingw64bin;C:msys64mingw64libgiomodules;C:Program FilesGitcmd;C:Program Files (x86)Windows Kits8.1Windows Performance Toolkit
Before changing «C:MinGW» into «C:MinGW-bak», I can use «ls» command in windows dos console.
After changing «C:MinGW» into «C:MinGW-bak», I can not use «ls» command in windows dos console.
Please forget about rst file. The rst file is a binary data file only. I use a demo program to read this rst file. The demo program works well in windows dos console and Msys console. But Even after changing «C:MinGW» into «MinGW-bak», the demo program can not run (can not find shared library) in «Msys2/mingw64 console». For sure there is no program about the rst file, demo program and its library. I choose them to test or check «Msys2/mingw64» because they are reliable, simple and easy to use. The problem is in that the demo program can not dynamically load its dynamic library in «Msys2/mingw64 console». I personally think that the issue is caused by path setting for «Msys2/ming64». In other words, my question is how to correctly set the path of «Msys2/ming64» so that it works well.
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: November 2, 2018 1:49 AM
To: Alexpux/MINGW-packages
Cc: songqingshan; Mention
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
you can use ls in cmd ?, did you export msysbin to PATH ? atleast that might explain some things.
well i noticed the rst extension and according to what i could find its a python docutils file, but it would not be the first time people have used extensions for other things. But just for curiosity try open it with notepad :), if its readable then its text, if it shows garbadge characters then its most likely as you say a binary. As for having ls avaliable in cmd, if msysbin was exported to PATH it would interfere with msys2 possibly breaking certain functions like the ability to correctly run this.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-435287498>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBU6h2vgzCxqtagZHD54zL-pqfnTGpks5uq-sSgaJpZM4X4db7>.
Hello Ralph,
The issue seems resolved. As I predict that it is path setting issue in msys2/mingw64.
When I use my profile to set path with adding a library path needed for search, It works.
When I use «set PATH=…», and «export PATH=…» commands in msys2/ming64 to add a library path needed for search , these commands are executed without any errors. But the library path is not added.
If either without modifying .profile in etc holders in msys2 or without using my profile, how can I add a new path to environment variable PATH directly.
I appreciate your help and your discussion with me.
Song
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: November 2, 2018 1:49 AM
To: Alexpux/MINGW-packages
Cc: songqingshan; Mention
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
you can use ls in cmd ?, did you export msysbin to PATH ? atleast that might explain some things.
well i noticed the rst extension and according to what i could find its a python docutils file, but it would not be the first time people have used extensions for other things. But just for curiosity try open it with notepad :), if its readable then its text, if it shows garbadge characters then its most likely as you say a binary. As for having ls avaliable in cmd, if msysbin was exported to PATH it would interfere with msys2 possibly breaking certain functions like the ability to correctly run this.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-435287498>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBU6h2vgzCxqtagZHD54zL-pqfnTGpks5uq-sSgaJpZM4X4db7>.
Custom paths can sometimes be a pain to setup in Msys or Cygwin, but glad you got some inspiration from our talks :). I remember setting paths like we did in old msys did not work entirely the same if we put those in etc/fstab since Msys2 is closer to Cygwin than Msys is, things sometimes got real screwy.
Instead we use cygpath for most of the path mangling, but it does have its flaws.
Put them in /etc/fstab though i cannot remember the exact way to write them, but alexy should be able to help with that. In old msys you just did it this way
C:yourpath /yourpath but if i remember correctly its a little different in msys2.
You can have multiple paths linked to windows mounted directories that way if you write each on a new line.
Also be sure not to delete this line from it -> «none / cygdrive binary,posix=0,noacl,user 0 0» or else you get cygwin paths with /cygdrive prefixed to all paths.
Ok just checked it, its written like this in cygwin
c:/yourpath /home/yourpath/ ntfs binary,posix=0,user 0 0
but since we allready have that portion in «none / cygdrive binary,posix=0,noacl,user 0 0» you should be able to just write c:/yourpath /home/yourpath/
also need to uncomment this in /home/.bash_profile
Set PATH so it includes user’s private bin if it exists
if [ -d «${HOME}/bin» ] ; then
PATH=»${HOME}/bin:${PATH}»
fi
and change all paths you link to in fstab to something like this c:/yourpath /home/bin/.
Means you could pretty much use visual studio or anything you like really from within msys2 :), but its a bit more complicated to setup than the old msys.
I enjoy our discussions. I really got inspiration from our talk. thanks.
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: November 3, 2018 4:18 PM
To: Alexpux/MINGW-packages
Cc: songqingshan; Mention
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
Custom paths can sometimes be a pain to setup in Msys or Cygwin, but glad you got some inspiration from our talks :). I remember setting paths like we did in old msys di not work entirely the same if we put those in etc/fstab since Msys2 is closer to Cygwin than Msys is, things sometimes got real screwy.
Instead we use cygpath for most of the path mangling, but it does have its flaws.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-435621637>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBU-fvOCQCaNBwSg6ExxXI4b5CkIRwks5urggdgaJpZM4X4db7>.
Just putting PATH in /etc/sfstas does not work thought.
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: November 3, 2018 4:23 PM
To: Alexpux/MINGW-packages
Cc: songqingshan; Mention
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
Put them in /etc/fstab though i cannot remember the exact way to write them, but alexy should be able to help with that. In old msys you just did it this way
C:yourpath /yourpath but if i remember correctly its a little different in msys2.
Also be sure not to delete this line from it -> «none / cygdrive binary,posix=0,noacl,user 0 0» or else you get cygwin paths with /cygdrive prefixed to all paths.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-435621947>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBUx4dnmR15I0nj1Gv5i2VE9S08jxJks5urglogaJpZM4X4db7>.
no you need to expand the path in /etc/fstab into PATH by either exporting it like this export PATH=$PATH:/yourpath where /yourpath is the posix version of c:/yourpath linked to in fstab.
Easier ways to do it but this way you dont end up mixing in a lot of unessesary stuff.
the resulting PATH should look something like this
«/mingw64/bin:/usr/local/bin:/usr/bin:/bin:/yourpath»
if /yourpath has a bin directory export that instead, since thats where binaries usually are so export PATH=$PATH:/yourpath/bin
if you have multiple paths in fstab just do it like this export PATH=$PATH:/yourpath1/bin:/yourpath2/bin etc.
Inserting this code after «none / cygdrive binary,posix=0,noacl,user 0 0» in /etc/fstab does not work. I attempt to use this code in command console, it does not work neither.
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: November 3, 2018 4:35 PM
To: Alexpux/MINGW-packages
Cc: songqingshan; Mention
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
also need to uncomment this in /home/.bash_profile
Set PATH so it includes user’s private bin if it exists
if [ -d «${HOME}/bin» ] ; then
PATH=»${HOME}/bin:${PATH}»
fi
and change all paths you link to in fstab to something like this c:/yourpath /home/bin/.
Means you could pretty much use visual studio or anything you like really from within msys2 :), but its a bit more complicated to setup than the old msys.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-435622674>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBUwhzWpi9jrZk7s9XngTQZuTJkwwAks5urgwqgaJpZM4X4db7>.
I put it in fstab file as follows
none / cygdrive binary,posix=0,noacl,user 0 0
export PATH=$PATH:C:/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64_win/compiler
or
none / cygdrive binary,posix=0,noacl,user 0 0
export PATH=$PATH:/C:/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64_win/compiler
or
none / cygdrive binary,posix=0,noacl,user 0 0
export PATH=$PATH:C:Program Files (x86)/
Common FilesIntelShared Librariesredistintel64_wincompiler
None of them works.
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: November 5, 2018 9:35 AM
To: Alexpux/MINGW-packages
Cc: songqingshan; Mention
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
no you need to expand the path in /etc/fstab into PATH by either exporting it like this export PATH=$PATH:/yourpath where /yourpath is the posix version of c:/yourpath linked to in fstab.
Easier ways to do it but this way you dont end up mixing in a lot of unessesary stuff.
the resulting PATH should look something like this
«/mingw64/bin:/usr/local/bin:/usr/bin:/bin:/yourpath»
if /yourpath has a bin directory export that instead, since thats where binaries usually are so export PATH=$PATH:/yourpath/bin
if you have multiple paths in fstab just do it like this export PATH=$PATH:/yourpath1/bin:/yourpath2/bin etc.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-435919111>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBU_yPPqXbUMinRTLR0Z7KQ8rb_8HNks5usFrQgaJpZM4X4db7>.
you mean that in fstab file they should like this,
«none / cygdrive binary,posix=0,noacl,user 0 0
export PATH=$PATH:C:/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64_win/compiler»
No, I try all what you said. they do not work.
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: November 5, 2018 9:35 AM
To: Alexpux/MINGW-packages
Cc: songqingshan; Mention
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
no you need to expand the path in /etc/fstab into PATH by either exporting it like this export PATH=$PATH:/yourpath where /yourpath is the posix version of c:/yourpath linked to in fstab.
Easier ways to do it but this way you dont end up mixing in a lot of unessesary stuff.
the resulting PATH should look something like this
«/mingw64/bin:/usr/local/bin:/usr/bin:/bin:/yourpath»
if /yourpath has a bin directory export that instead, since thats where binaries usually are so export PATH=$PATH:/yourpath/bin
if you have multiple paths in fstab just do it like this export PATH=$PATH:/yourpath1/bin:/yourpath2/bin etc.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-435919111>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBU_yPPqXbUMinRTLR0Z7KQ8rb_8HNks5usFrQgaJpZM4X4db7>.
uh no like this ->
after the
none / cygdrive binary,posix=0,noacl,user 0 0 which is allready there.
put C:/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64_win/compiler /intelc <- notice this.
now open a bash shell and do export PATH=$PATH:/intelc
you might run into trouble with paths that have spaces in them, in that case put «» around C:/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64_win/compiler so that it looks like this
«C:/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64_win/compiler» /intelc
Yep definatly trouble with that, just tested.
If i use a short path like c:dmbin it works but C:/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64_win/compiler does not.
Unfortunatly it seems even putting it in braces is not enough, so only other solution would be doing it with a batch file, it will be rather messy though.
Ok had a look at the cygwin mount tables and theres a workaround for the substitution.
the spaces need to be escaped with 40 so it becomes C:/Program40Files40(x86)/Common40Files/Intel/Shared40Libraries/redist/intel64_win/compiler .
https://cygwin.com/cygwin-ug-net/using.html
another way is creating a symlink to C:/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64_win/compiler in say C:/intel and then use that as path.
«C:/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64_win/compiler» is only what I need to add.
I do not understand why need to put
«C:/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64_win/compiler /intelc»
or
«C:/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64_win/compiler /intelc <»
or «C:/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64_win/compiler /intelc <- »
what is «/intelc» used for?
Anyway, these do not work.
…
putting «C:/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64_win/compiler» /intelc only can add /intelc.
I do not understand why I should have /intelc. what is /intelc used for.
…
This way does not work.
…
________________________________
From: Ralph Engels <notifications@github.com>
Sent: November 6, 2018 2:33 AM
To: Alexpux/MINGW-packages
Cc: songqingshan; Mention
Subject: Re: [Alexpux/MINGW-packages] error while loading shared libraries: ?: cannot open shared object file: No such file or directory (#4588)
Ok had a look at the cygwin mount tables and theres a workaround for the substitution.
the spaces need to be escaped with 40 so it becomes C:/Program40Files40(x86)/Common40Files/Intel/Shared40Libraries/redist/intel64_win/compiler .
https://cygwin.com/cygwin-ug-net/using.html
Chapter 3. Using Cygwin<https://cygwin.com/cygwin-ug-net/using.html>
cygwin.com
The Cygwin DLL supports both POSIX- and Win32-style paths. Directory delimiters may be either forward slashes or backslashes. Paths using backslashes or starting with a drive letter are always handled as Win32 paths.
another way is creating a symlink to C:/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64_win/compiler in say C:/intel and then use that as path.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub<https://github.com/Alexpux/MINGW-packages/issues/4588#issuecomment-436171145>, or mute the thread<https://github.com/notifications/unsubscribe-auth/ApTBU8jyfn1oHg2U1MwlIP0MXWn2k5TRks5usUlhgaJpZM4X4db7>.
/intelc becomes the new posix path of C:/Program Files (x86)/Common Files/Intel/Shared Libraries/redist/intel64_win/compiler.
so instead of that long windows path you have a shorter one thats easier to work with :).
There is a list of common errors I often see in Ubuntu. There is problem with merge list, then there is BADSIG error, and a number of common Ubuntu update errors.
One of such common errors which I often see while installing a program from its source code is error while loading shared libraries. The full error generally looks like this:
error while loading shared libraries:
cannot open shared object file: No such file or directory
For example, I was trying to use FreeRADIUS server and it showed me this error:
radiusd: error while loading shared libraries:
libfreeradius-radius-2.1.10.so:
cannot open shared object file: No such file or directory
The reason behind this error is that the libraries of the program have been installed in a place where dynamic linker cannot find it.
Let me show you how you can go about fixing this issue.
One quick way to fix this “error while loading shared libraries” automatically is to use ldconfig.
All you need to do is to open terminal (Ctrl+Alt+T) and type the following command:
sudo /sbin/ldconfig -v
This one liner should solve the problem in most cases. However, if it doesn’t, I have discussed another method to handle this error. But before that, let me tell you what does the above command do.
What are shared object files? How does the above command fixes the issue?
You see, in C/C++, a .so (shared object) is a compiled library file. It is called shared object because this library file can be shared by several programs. These generated libraries are usually located in /lib or /usr/lib directories.
Now if you wonder how did this tiny command fixed this problem, you should read the man page of ldconfig which says:
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.
I hope this quick fix helps you in eliminating the nasty error while loading shared libraries message in Ubuntu and other Linux.
If not, you can do some investigation and try to fix the issue the way it is mentioned in the next section.
The above discussed method fixes the issue if the library in question is available in your system. But that may not always be the case.
If you do not have the program installed on your system, you won’t have its library file. The ldconfig cannot do anything if there is no library file in the first place.
So, the alternate method is to install the required program and it should create the library automatically.
Let me show it to you by an example. Let’s say you see this error:
error while loading shared libraries: libgobject-2.0.so.0: cannot open shared object file: No such file or directory
The problem is with libgobject version 2.0. The version number is important because some programs depend on a specific version of the library and if they don’t find, they complain about it.
Now, apt provides the search option that can be used for searching a package and knowing its version before installing it.
[email protected]:~$ apt search libgobject
Sorting... Done
Full Text Search... Done
librust-gobject-sys-dev/focal 0.9.0-2 amd64
FFI bindings to libgobject-2.0 - Rust source code
Now, this librust-gobject-sys-dev package could be what you need if you know that you were trying to run a Rust program. But what if it was a Python program you were running that complained about it?
You can widen your search by removing the lib from the package name while searching. The lib signifies library and libraries may be provided by a generic package that could be named gobject-xyz.
It would be a good idea to search for the string in the names of the package (instead of description) to get more concise results.
[email protected]:~$ apt search --names-only gobject
Sorting... Done
Full Text Search... Done
gobject-introspection/focal-updates 1.64.1-1~ubuntu20.04.1 amd64
Generate interface introspection data for GObject libraries
libavahi-gobject-dev/focal 0.7-4ubuntu7 amd64
Development headers for the Avahi GObject library
libavahi-gobject0/focal 0.7-4ubuntu7 amd64
Avahi GObject library
libcairo-gobject-perl/focal,now 1.005-2 amd64 [installed,automatic]
integrate Cairo into the Glib type system in Perl
libcairo-gobject2/focal,now 1.16.0-4ubuntu1 amd64 [installed,automatic]
Cairo 2D vector graphics library (GObject library)
libghc-gi-gobject-dev/focal 2.0.19-1build1 amd64
GObject bindings
libghc-gi-gobject-doc/focal,focal 2.0.19-1build1 all
GObject bindings; documentation
In the above truncated output, you’ll have to see if the package is related to the original program you were trying to run. You must also check the version of the library provided.
Once you have identified the correct package, install it like this:
sudo apt install package_name
Once installed, you may run the ldconfig command again to update the cache:
sudo /sbin/ldconfig -v
This method requires some effort on your end but this is how the dependencies are handled.
Nothing works, what now?
If you are unfortunate enough, the above methods might not work for you. What can you do?
First, keep in mind that the shared libraries may be used from other packages in some cases. If you were trying to run XYZ program and ABC program installs the correct version of the shared library, it may (or may not) work for you. You can give it a hit and trial.
Second, if you are trying to run a program which is too old or too new, it may require a library version which is not available for your Linux distribution.
What you may do is to check if you can use some other version of the program. For example, using Eclipse version 3 instead of version 4. This may help your case.
The other way would be to check the developers website or forums and see if you can manually install the correct version of the library from its source code. That requires a lot of effort (in 2020) but you don’t have a lot of options.
Did it work for you?
I hope I have make things a bit more clear for you. Did you manage to fix the issue of shared libraries in your system? If you have questions, suggestions, feel free to drop a comment. Ciao
Библиотеки
Библиотека — в языке C, файл содержащий объектный код, который может быть присоединен к использующей библиотеку программе на этапе линковки. Фактически библиотека это набор особым образом скомпонованных объектных файлов.
Назначение библиотек — предоставить программисту стандартный механизм повторного использования кода, причем механизм простой и надёжный.
С точки зрения операционной системы и прикладного программного обеспечения библиотеки бывают статическими и разделяемыми (динамическими).
Код статических библиотек включается в состав исполняемого файла в ходе линковки последнего. Библиотека оказывается «зашитой» в файл, код библиотеки «сливается» с остальным кодом файла. Программа использующая статические библиотеки становиться автономной и может быть запущена практически на любом компьютере с подходящей архитектурой и операционной системой.
Код разделяемой библиотеки загружается и подключается к коду программы операционной системой, по запросу программы в ходе её исполнения. В состав исполняемого файла программы код динамической библиотеки не входит, в исполняемый файл включается только ссылка на библиотеку. В результате, программа использующая разделяемые библиотеки перестает быть автономной и может быть успешно запущена только в системе где задействованные библиотеки установлены.
Парадигма разделяемых библиотек предоставляет три существенных преимущества:
1. Многократно сокращается размер исполняемого файла. В системе, включающей множество бинарных файлов, использующих один и тот же код, отпадает необходимость хранить копию этого кода для каждого исполняемого файла.
2. Код разделяемой библиотеки используемый несколькими приложениями храниться в оперативной памяти в одном экземпляре (на самом деле не всё так просто…), в результате сокращается потребность системы в доступной оперативной памяти.
3. Отпадает необходимость пересобирать каждый исполняемый файл в случае внесения изменений в код общей для них библиотеки. Изменения и исправления кода динамической библиотеки автоматически отразятся на каждой из использующих её программ.
Без парадигмы разделяемых библиотек не существовало бы прекомпиллированных (бинарных) дистрибутивов Linux (да ни каких бы не существовало). Представьте размеры дистрибутива, в каждый бинарный файл которого, был бы помещен код стандартной библиотеки C (и всех других подключаемых библиотек). Так же представьте что пришлось бы делать для того, что бы обновить систему, после устранения критической уязвимости в одной из широко задействованных библиотек…
Теперь немного практики.
Для иллюстрации воспользуемся набором исходных файлов из предыдущего примера. В нашу самодельную библиотеку поместим код (реализацию) функций first() и second().
В Linux принята следующая схема именования файлов библиотек (хотя соблюдается она не всегда) — имя файла библиотеки начинается с префикса lib, за ним следует собственно имя библиотеки, в конце расширение .a (archive) — для статической библиотеки, .so (shared object) — для разделяемой (динамической), после расширения через точку перечисляются цифры номера версии (только для динамической библиотеки). Имя, соответствующего библиотеке заголовочного файла (опять же как правило), состоит из имени библиотеки (без префикса и версии) и расширения .h. Например: libogg.a, libogg.so.0.7.0, ogg.h.
В начале создадим и используем статическую библиотеку.
Функции first() и second() составят содержимое нашей библиотеки libhello. Имя файла библиотеки, соответственно, будет libhello.a. Библиотеке сопоставим заголовочный файл hello.h.
/* hello.h */ void first(void); void second(void); Разумеется, строки: #include "first.h" #include "second.h" в файлах main.c, first.c и second.c необходимо заменить на: #include "hello.h" Ну а теперь, введем следующую последовательность команд: $ gcc -Wall -c first.c $ gcc -Wall -c second.c $ ar crs libhello.a first.o second.o $ file libhello.a libhello.a: current ar archive
Как уже было сказано — библиотека это набор объектных файлов. Первыми двумя командами мы и создали эти объектные файлы.
Далее необходимо объектные файлы скомпоновать в набор. Для этого используется архиватор ar — утилита «склеивает» несколько файлов в один, в полученный архив включает информацию требуемую для восстановления (извлечения) каждого индивидуального файла (включая его атрибуты принадлежности, доступа, времени). Какого-либо «сжатия» содержимого архива или иного преобразования хранимых данных при этом не производится.
Опция c arname — создать архив, если архив с именем arname не существует он будет создан, в противном случае файлы будут добавлены к имеющемуся архиву.
Опция r — задает режим обновления архива, если в архиве файл с указанным именем уже существует, он будет удален, а новый файл дописан в конец архива.
Опция s — добавляет (обновляет) индекс архива. В данном случае индекс архива это таблица, в которой для каждого определенного в архивируемых файлах символического имени (имени функции или блока данных) сопоставлено соответствующее ему имя объектного файла. Индекс архива необходим для ускорения работы с библиотекой — для того чтобы найти нужное определение, отпадает необходимость просматривать таблицы символов всех файлов архива, можно сразу перейти к файлу, содержащему искомое имя. Просмотреть индекс архива можно с помощью уже знакомой утилиты nm воспользовавшись её опцией -s (так же будут показаны таблицы символов всех объектных файлов архива):
$ nm -s libhello.a Archive index: first in first.o second in second.o first.o: 00000000 T first U puts second.o: U puts 00000000 T second
Для создания индекса архива существует специальная утилита ranlib. Библиотеку libhello.a можно было сотворить и так:
$ ar cr libhello.a first.o second.o
$ ranlib libhello.a
Впрочем библиотека будет прекрасно работать и без индекса архива.
Теперь воспользуемся нашей библиотекой:
$ gcc -Wall -c main.c
$ gcc -o main main.o -L. -lhello
$ ./main
First function…
Second function…
Main function…
Работает…
Ну теперь комментарии… Появились две новые опции gcc:
Опция -lname — передаётся линковщику, указывает на необходимость подключить к исполняемому файлу библиотеку libname. Подключить значит указать, что такие-то и такие-то функции (внешние переменные) определены в такой-то библиотеке. В нашем примере библиотека статическая, все символьные имена будут ссылаться на код находящийся непосредственно в исполняемом файле. Обратите внимание в опции -l имя библиотеки задается как name без приставки lib.
Опция -L/путь/к/каталогу/с/библиотеками — передаётся линковщику, указывает путь к каталогу содержащему подключаемые библиотеки. В нашем случае задана точка ., линковщик сначала будет искать библиотеки в текущем каталоге, затем в каталогах определённых в системе.
Здесь необходимо сделать небольшое замечание. Дело в том, что для ряда опций gcc важен порядок их следования в командной строке. Так линковщик ищет код, соответствующий указанным в таблице символов файла именам в библиотеках, перечисленных в командной строке после имени этого файла. Содержимое библиотек перечисленных до имени файла линковщик игнорирует:
$ gcc -Wall -c main.c
$ gcc -o main -L. -lhello main.o
main.o: In function `main’:
main.c:(.text+0xa): undefined reference to `first’
main.c:(.text+0xf): undefined reference to `second’
collect2: ld returned 1 exit status
$ gcc -o main main.o -L. -lhello
$ ./main
First function…
Second function…
Main function…
Такая особенность поведения gcc обусловлена желанием разработчиков предоставить пользователю возможность по разному комбинировать файлы с библиотеками, использовать пересекающие имена… На мой взгляд, если возможно, лучше этим не заморачиваться. В общем подключаемые библиотеки необходимо перечислять после имени ссылающегося на них файла.
Существует альтернативный способ указания местоположения библиотек в системе. В зависимости от дистрибутива, переменная окружения LD_LIBRARY_PATH или LIBRARY_PATH может хранить список разделенных знаком двоеточия каталогов, в которых линковщик должен искать библиотеки. Как правило, по умолчанию эта переменная вообще не определена, но ни чего не мешает её создать:
$ echo $LD_LIBRARY_PATH
$ gcc -o main main.o -lhello
/usr/lib/gcc/i686-pc-linux-gnu/4.4.3/../../../../i686-pc-linux-gnu/bin/ld: cannot find -lhello
collect2: выполнение ld завершилось с кодом возврата 1
$ export LIBRARY_PATH=.
$ gcc -o main main.o -lhello
$ ./main
First function…
Second function…
Main function…
Манипуляции с переменными окружения полезны при создании и отладке собственных библиотек, а так же если возникает необходимость подключить к приложению какую-нибудь нестандартную (устаревшую, обновленную, изменённую — в общем отличную от включенной в дистрибутив) разделяемую библиотеку.
Теперь создадим и используем библиотеку динамическую.
Набор исходных файлов остается без изменения. Вводим команды, смотрим что получилось, читаем комментарии:
$ gcc -Wall -fPIC -c first.c
$ gcc -Wall -fPIC -c second.c
$ gcc -shared -o libhello.so.2.4.0.5 -Wl,-soname,libhello.so.2 first.o second.o
Что получили в результате?
$ file libhello.so.2.4.0.5
libhello.so.2.4.0.5: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, not stripped
Файл libhello.so.2.4.0.5, это и есть наша разделяемая библиотека. Как её использовать поговорим чуть ниже.
Теперь комментарии:
Опция -fPIC — требует от компилятора, при создании объектных файлов, порождать позиционно-независимый код (PIC — Position Independent Code), его основное отличие в способе представления адресов. Вместо указания фиксированных (статических) позиций, все адреса вычисляются исходя из смещений заданных в глобальной таблицы смещений (global offset table — GOT). Формат позиционно-независимого кода позволяет подключать исполняемые модули к коду основной программы в момент её загрузки. Соответственно, основное назначение позиционно-независимого кода — создание динамических (разделяемых) библиотек.
Опция -shared — указывает gcc, что в результате должен быть собран не исполняемый файл, а разделяемый объект — динамическая библиотека.
Опция -Wl,-soname,libhello.so.2 — задает soname библиотеки. О soname подробно поговорим в следующем абзаце. Сейчас обсудим формат опции. Сея странная, на первый взгляд, конструкция с запятыми предназначена для непосредственного взаимодействия пользователя с линковщиком. По ходу компиляции gcc вызывает линковщик автоматически, автоматически же, по собственному усмотрению, gcc передает ему необходимые для успешного завершения задания опции. Если у пользователя возникает потребность самому вмешаться в процесс линковки он может воспользоваться специальной опцией gcc -Wl,-option,value1,value2…. Что означает передать линковщику (-Wl) опцию -option с аргументами value1, value2 и так далее. В нашем случае линковщику была передана опция -soname с аргументом libhello.so.2.
Теперь о soname. При создании и распространении библиотек встает проблема совместимости и контроля версий. Для того чтобы система, конкретно загрузчик динамических библиотек, имели представление о том библиотека какой версии была использована при компиляции приложения и, соответственно, необходима для его успешного функционирования, был предусмотрен специальный идентификатор — soname, помещаемый как в файл самой библиотеки, так и в исполняемый файл приложения. Идентификатор soname это строка, включающая имя библиотеки с префиксом lib, точку, расширение so, снова точку и оду или две (разделенные точкой) цифры версии библиотеки — libname.so.x.y. То есть soname совпадает с именем файла библиотеки вплоть до первой или второй цифры номера версии. Пусть имя исполняемого файла нашей библиотеки libhello.so.2.4.0.5, тогда soname библиотеки может быть libhello.so.2. При изменении интерфейса библиотеки её soname необходимо изменять! Любая модификация кода, приводящая к несовместимости с предыдущими релизами должна сопровождаться появлением нового soname.
Как же это все работает? Пусть для успешного исполнения некоторого приложения необходима библиотека с именем hello, пусть в системе таковая имеется, при этом имя файла библиотеки libhello.so.2.4.0.5, а прописанное в нем soname библиотеки libhello.so.2. На этапе компиляции приложения, линковщик, в соответствии с опцией -lhello, будет искать в системе файл с именем libhello.so. В реальной системе libhello.so это символическая ссылка на файл libhello.so.2.4.0.5. Получив доступ к файлу библиотеки, линковщик считает прописанное в нем значение soname и наряду с прочим поместит его в исполняемый файл приложения. Когда приложение будет запущено, загрузчик динамических библиотек получит запрос на подключение библиотеки с soname, считанным из исполняемого файла, и попытается найти в системе библиотеку, имя файла которой совпадает с soname. То есть загрузчик попытается отыскать файл libhello.so.2. Если система настроена корректно, в ней должна присутствовать символическая ссылка libhello.so.2 на файл libhello.so.2.4.0.5, загрузчик получит доступ к требуемой библиотеки и далее не задумываясь (и ни чего более не проверяя) подключит её к приложению. Теперь представим, что мы перенесли откомпилированное таким образом приложение в другую систему, где развернута только предыдущая версия библиотеки с soname libhello.so.1. Попытка запустить программу приведет к ошибке, так как в этой системе файла с именем libhello.so.2 нет.
Таким образом, на этапе компиляции линковщику необходимо предоставить файл библиотеки (или символическую ссылку на файл библиотеки) с именем libname.so, на этапе исполнения загрузчику потребуется файл (или символическая ссылка) с именем libname.so.x.y. При чем имя libname.so.x.y должно совпадать со строкой soname использованной библиотеки.
В бинарных дистрибутивах, как правило, файл библиотеки libhello.so.2.4.0.5 и ссылка на него libhello.so.2 будут помещены в пакет libhello, а необходимая только для компиляции ссылка libhello.so, вместе с заголовочным файлом библиотеки hello.h будет упакована в пакет libhello-devel (в devel пакете окажется и файл статической версии библиотеки libhello.a, статическая библиотека может быть использована, также только на этапе компиляции). При распаковке пакета все перечисленные файлы и ссылки (кроме hello.h) окажутся в одном каталоге.
Пример именования библиотек в Linux. Ubuntu
Убедимся, что заданная строка soname действительно прописана в файле нашей библиотеки. Воспользуемся мега утилитой objdump с опцией -p:
$ objdump -p libhello.so.2.4.0.5 | grep SONAME SONAME libhello.so.2
Утилита objdump — мощный инструмент, позволяющий получить исчерпывающую информацию о внутреннем содержании (и устройстве) объектного или исполняемого файла. В man странице утилиты сказано, что objdump прежде всего будет полезен программистам, создающими средства отладки и компиляции, а не просто пишущих какие-нибудь прикладные программы В частности с опцией -d это дизассемблер. Мы воспользовались опцией -p — вывести различную метаинформацию о объектном файле.
В приведенном примере создания библиотеки мы неотступно следовали принципам раздельной компиляции. Разумеется скомпилировать библиотеку можно было бы и вот так, одним вызовом gcc:
$ gcc -shared -Wall -fPIC -o libhello.so.2.4.0.5 -Wl,-soname,libhello.so.2 first.c second.c
Теперь попытаемся воспользоваться получившейся библиотекой:
$ gcc -Wall -c main.c
$ gcc -o main main.o -L. -lhello -Wl,-rpath,.
/usr/bin/ld: cannot find -lhello
collect2: ld returned 1 exit status
Линковщик ругается. Вспоминаем, что было сказано выше о символических ссылках. Создаем libhello.so и повторяем попытку:
$ ln -s libhello.so.2.4.0.5 libhello.so
$ gcc -o main main.o -L. -lhello -Wl,-rpath,.
Теперь все довольны. Запускаем созданный бинарник:
$ ./main
./main: error while loading shared libraries: libhello.so.2: cannot open shared object file: No such file or directory
Ошибка… Ругается загрузчик, не может найти библиотеку libhello.so.2. Убедимся, что в исполняемом файле действительно прописана ссылка на libhello.so.2:
$ objdump -p main | grep NEEDED NEEDED libhello.so.2 NEEDED libc.so.6
Создаем соответствующую ссылку и повторно запускаем приложение:
$ ln -s libhello.so.2.4.0.5 libhello.so.2
$ ./main
First function…
Second function…
Main function…
Заработало… Теперь комментарии по новым опциям gcc.
Опция -Wl,-rpath,. — уже знакомая конструкция, передать линковщику опцию -rpath с аргументом .. С помощью -rpath в исполняемый файл программы можно прописать дополнительные пути по которым загрузчик разделяемых библиотек будет производить поиск библиотечных файлов. В нашем случае прописан путь . — поиск файлов библиотек будет начинаться с текущего каталога.
$ objdump -p main | grep RPATH RPATH .
Благодаря указанной опции, при запуске программы отпала необходимость изменять переменные окружения. Понятно, что если перенести программу в другой каталог и попытаться запустить, файл библиотеки будет не найден и загрузчик выдаст сообщение об ошибке:
$ mv main ..
$ ../main
First function…
Second function…
Main function…
$ cd ..
$ ./main
./main: error while loading shared libraries: libhello.so.2: cannot open shared object file: No such file or directory
Узнать какие разделяемые библиотеки необходимы приложению можно и с помощью утилиты ldd:
$ ldd main
linux-vdso.so.1 => (0x00007fffaddff000)
libhello.so.2 => ./libhello.so.2 (0x00007f9689001000)
libc.so.6 => /lib/libc.so.6 (0x00007f9688c62000)
/lib64/ld-linux-x86-64.so.2 (0x00007f9689205000)
В выводе ldd для каждой требуемой библиотеки указывается её soname и полный путь к файлу библиотеки, определённый в соответствии с настройками системы.
Сейчас самое время поговорить о том где в системе положено размещать файлы библиотек, где загрузчик пытается их найти и как этим процессом управлять.
В соответствии с соглашениями FHS (Filesystem Hierarchy Standard) в системе должны быть два (как минимум) каталога для хранения файлов библиотек:
/lib — здесь собраны основные библиотеки дистрибутива, необходимые для работы программ из /bin и /sbin;
/usr/lib — здесь хранятся библиотеки необходимые прикладным программам из /usr/bin и /usr/sbin;
Соответствующие библиотекам заголовочные файлы должны находиться в каталоге /usr/include.
Загрузчик по умолчанию будет искать файлы библиотек в этих каталогах.
Кроме перечисленных выше, в системе должен присутствовать каталог /usr/local/lib — здесь должны находиться библиотеки, развернутые пользователем самостоятельно, минуя систему управления пакетами (не входящие в состав дистрибутива). Например в этом каталоге по умолчанию окажутся библиотеки скомпилированные из исходников (программы установленные из исходников будут размещены в /usr/local/bin и /usr/local/sbin, разумеется речь идет о бинарных дистрибутивах). Заголовочные файлы библиотек в этом случае будут помещены в /usr/local/include.
В ряде дистрибутивов (в Ubuntu) загрузчик не настроен просматривать каталог /usr/local/lib, соответственно, если пользователь установит библиотеку из исходников, система её не увидит. Сиё авторами дистрибутива сделано специально, что бы приучить пользователя устанавливать программное обеспечение только через систему управления пакетами. Как поступить в данном случае будет рассказано ниже.
В действительности, для упрощения и ускорения процесса поиска файлов библиотек, загрузчик не просматривает при каждом обращении указанные выше каталоги, а пользуется базой данных, хранящейся в файле /etc/ld.so.cache (кэшем библиотек). Здесь собрана информация о том, где в системе находится соответствующий данному soname файл библиотеки. Загрузчик, получив список необходимых конкретному приложению библиотек (список soname библиотек, заданных в исполняемом файле программы), посредством /etc/ld.so.cache определяет путь к файлу каждой требуемой библиотеки и загружает её в память. Дополнительно, загрузчик может просмотреть каталоги перечисленные в системных переменных LD_LIBRARY_PATH, LIBRARY_PATH и в поле RPATH исполняемого файла (смотри выше).
Для управления и поддержания в актуальном состоянии кэша библиотек используется утилита ldconfig. Если запустить ldconfig без каких-либо опций, программа просмотрит каталоги заданные в командной строке, доверенные каталоги /lib и /usr/lib, каталоги перечисленные в файле /etc/ld.so.conf. Для каждого файла библиотеки, оказавшегося в указанных каталогах, будет считано soname, создана основанная на soname символическая ссылка, обновлена информация в /etc/ld.so.cache.
Убедимся в сказанном:
$ ls
hello.h libhello.so libhello.so.2.4.0.5 main.c
$ gcc -Wall -o main main.c -L. -lhello
$ ./main
./main: error while loading shared libraries: libhello.so.2: cannot open shared object file: No such file or directory
$ sudo ldconfig /полный/путь/к/катаогу/c/примером
$ ls
hello.h libhello.so libhello.so.2 libhello.so.2.4.0.5 main main.c
$ ./main
First function…
Second function…
Main function…
$ sudo ldconfig
$ ./main
./main: error while loading shared libraries: libhello.so.2: cannot open shared object file: No such file or directory
Первым вызовом ldconfig мы внесли в кэш нашу библиотеку, вторым вызовом исключили. Обратите внимание, что при компиляции main была опущена опция -Wl,-rpath,., в результате загрузчик проводил поиск требуемых библиотек только в кэше.
Теперь должно быть понятно как поступить если после установки библиотеки из исходников система её не видит. Прежде всего необходимо внести в файл /etc/ld.so.conf полный путь к каталогу с файлами библиотеки (по умолчанию /usr/local/lib). Формат /etc/ld.so.conf — файл содержит список разделённых двоеточием, пробелом, табуляцией или символом новой строки, каталогов, в которых производится поиск библиотек. После чего вызвать ldconfig без каких-либо опций, но с правами суперпользователя. Всё должно заработать.
Ну и в конце поговорим о том как уживаются вместе статические и динамические версии библиотек. В чем собственно вопрос? Выше, когда обсуждались принятые имена и расположение файлов библиотек было сказано, что файлы статической и динамической версий библиотеки хранятся в одном и том же каталоге. Как же gcc узнает какой тип библиотеки мы хотим использовать? По умолчанию предпочтение отдается динамической библиотеки. Если линковщик находит файл динамической библиотеки, он не задумываясь цепляет его к исполняемому файлу программы:
$ ls
hello.h libhello.a libhello.so libhello.so.2 libhello.so.2.4.0.5 main.c
$ gcc -Wall -c main.c
$ gcc -o main main.o -L. -lhello -Wl,-rpath,.
$ ldd main
linux-vdso.so.1 => (0x00007fffe1bb0000)
libhello.so.2 => ./libhello.so.2 (0x00007fd50370b000)
libc.so.6 => /lib/libc.so.6 (0x00007fd50336c000)
/lib64/ld-linux-x86-64.so.2 (0x00007fd50390f000)
$ du -h main
12K main
Обратите внимание на размер исполняемого файла программы. Он минимально возможный. Все используемые библиотеки линкуются динамически.
Существует опция gcc -static — указание линковщику использовать только статические версии всех необходимых приложению библиотек:
$ gcc -static -o main main.o -L. -lhello
$ file main
main: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), statically linked, for GNU/Linux 2.6.15, not stripped
$ ldd main
не является динамическим исполняемым файлом
$ du -h main
728K main
Размер исполняемого файла в 60 раз больше, чем в предыдущем примере — в файл включены стандартные библиотеки языка C. Теперь наше приложение можно смело переносить из каталога в каталог и даже на другие машины, код библиотеки hello внутри файла, программа полностью автономна.
Как же быть если необходимо осуществить статическую линковку только части использованных библиотек? Возможный вариант решения — сделать имя статической версии библиотеки отличным от имени разделяемой, а при компиляции приложения указывать какую версию мы хотим использовать на этот раз:
$ mv libhello.a libhello_s.a
$ gcc -o main main.o -L. -lhello_s
$ ldd main
linux-vdso.so.1 => (0x00007fff021f5000)
libc.so.6 => /lib/libc.so.6 (0x00007fd0d0803000)
/lib64/ld-linux-x86-64.so.2 (0x00007fd0d0ba4000)
$ du -h main
12K main
Так как размер кода библиотеки libhello ничтожен,
$ du -h libhello_s.a
4,0K libhello.a
Убедимся, что заданная строка soname действительно
размер получившегося исполняемого файла практически не отличается от размера файла созданного с использованием динамической линковки.
http://pyviy.blogspot.ru/2010/12/gcc.html