1. 程式人生 > >Linux動態庫載入失敗/設定執行時搜尋路徑

Linux動態庫載入失敗/設定執行時搜尋路徑

程式執行時有以下錯誤
./dom1: error while loading shared libraries: libmemcached.so.11: cannot open shared object file: No such file or directory
動態庫載入失敗

1、首先應該使用命令檢視所載入的庫

 ldd ./dom1
    linux-vdso.so.1 =>  (0x00007ffdb4368000)
    libmemcached.so.11 => not found
    libc.so.6 => /lib64/libc.so.6 (0x00007f4174962000
) /lib64/ld-linux-x86-64.so.2 (0x00007f4174d33000)

看看所載入的庫
2、使用命令檢視載入庫時所搜尋的路徑

LD_DEBUG=libs ./dom1 -v
46688:  find library=libmemcached.so.11 [0]; searching
     46688:  search cache=/etc/ld.so.cache
     46688:  search path=/lib64/tls/x86_64:/lib64/tls:/lib64/x86_64:/lib64:/usr/lib64/tls/x86_64:/usr/lib64/tls:/usr/lib64/x86_64:/usr/
lib64 (system search path) 46688: trying file=/lib64/tls/x86_64/libmemcached.so.11 46688: trying file=/lib64/tls/libmemcached.so.11 46688: trying file=/lib64/x86_64/libmemcached.so.11 46688: trying file=/lib64/libmemcached.so.11 46688: trying file=/usr/lib64/tls/x86_64/libmemcached.so.11
46688: trying file=/usr/lib64/tls/libmemcached.so.11 46688: trying file=/usr/lib64/x86_64/libmemcached.so.11 46688: trying file=/usr/lib64/libmemcached.so.11 46688: ./dom1: error while loading shared libraries: libmemcached.so.11: cannot open shared object file: No such file or directory

可以看出大多在lib64中搜索,由於我沒有lib64這個目錄我的是lib目錄所以就報加載出錯。
解決方案
1、修改搜尋目錄
2、給你lib中的庫生成一個lib64的軟連線 就可以解決

3,設定執行時搜尋路徑的方式,使用-rpath或-R連線選項來指定執行時搜尋路徑,其優先順序高於LD_LIBRARY_PATH。

$ g++ -o dom1 -L. -I. main.cpp -Wl,-rpath .
// 或
$ g++ -o dom1 -L. -I. main.cpp -Wl,-rpath=.
// 或
$ g++ -o dom1-L. -I. main.cpp -Wl,-R.