繼續上一篇《 linux下so動態庫一些鮮爲人知的祕密(中) 》介紹so搜索路徑,還有一個相似於-path,叫LD_RUN_PATH環境變量, 它也是把路徑編譯進可執行文件內,不一樣的是它只設置RPATH。html
[stevenrao]
$
g++ -o demo -L /tmp/ -ltmp main.cpp
[stevenrao]
$
readelf -d demo
Dynamic section at offset 0xb98 contains 25 entries:
Tag Type Name/Value
0x0000000000000001 (NEEDED) Shared library: [libtmp.so]
....
0x000000000000000f
(RPATH) Library rpath: [/tmp/]
另外還能夠經過配置
/etc/ld.so.conf,在其中加入一行
/tmp/
這個配置項也是隻對運行期有效,而且是全局用戶都生效,須要root權限修改,修改完後須要使用命令
ldconfig 將 /etc/ld.so.conf 加載到
ld.so.cache中,避免重啓系統就能夠當即生效。
除了前面介紹的那些搜索路徑外,還有缺省搜索路徑/usr/lib/ /lib/ 目錄,能夠經過-z nodefaultlib編譯選項禁止搜索缺省路徑。
[stevenrao] $
g++ -o demo -z nodefaultlib -L/tmp -ltmp main.cpp
[stevenrao] $
./demo
./demo: error while loading shared libraries:
libstdc++.so.6: cannot open shared object file
這麼多搜索路徑,他們有個前後順序以下
一、RUMPATH 優先級最高
二、RPATH 其次
三、LD_LIBRARY_PATH
四、/etc/ld.so.cache
五、/usr/lib/ /lib/
查看一個程序搜索其各個動態庫另外一個簡單的辦法是使用 LD_DEBUG這個環境變量;
[stevenrao] $
export LD_DEBUG=libs
[stevenrao] $
./demo
下一篇介紹動態庫內符號問題