(原)g++編譯後運行時無法連結動態庫的解決方案

來源:互聯網
上載者:User

g++編譯後運行時無法連結動態庫的解決方案:

問題發現:

$
g++ -Wall -o hellobrowser.exec hellobrowser.c -I/usr/local/include
-L/usr/local/lib -lmicrohttpd -ldl

$
./hellobrowser.exec

error
while loading shared libraries: libmicrohttpd.so.10: cannot open
shared object file: No such file or directory

$
whereis libmicrohttpd

發現/usr/local/lib下有這個庫

$
cd /usr/local/lib

$
find libmicrohttpd.so.10

的確有這個檔案。

這是因為動態庫預設只會在/usr/lib下找。不會去/usr/local/lib找。

解決方案:

法1:sudo
vi /etc/ld.so.conf

添加一行:

/usr/local/lib

然後sudo
ldconfig使得生效。這樣動態庫就會去/usr/local/lib找了。

法2:

g++ -Wall -o hellobrowser.exec hellobrowser.c -I/usr/local/include -L/usr/local/lib -lmicrohttpd -ldl -Wl,-R /usr/local/lib

 

法3:
$ ln -s /usr/local/lib/libmicrohttpd.so.10 /usr/lib/libmicrohttpd.so.10
# ln -s /usr/local/lib/libmicrohttpd.so /usr/lib/libmicrohttpd.so


推薦法1和法2.

 

分析解釋:

預設情況下,編譯器只會使用/lib和/usr/lib這兩個目錄下的庫檔案。

雖然g++
-L/usr/local/lib雖然能讓連結器找到庫進行連結,但是運行時連結器卻找不到這個庫,如果要讓軟體執行階段程式庫檔案的路徑也得到擴充,那麼我們需要增加這個庫路徑加上-Wl,-R,即添加g++參數“-Wl,-R
動態庫庫路徑”。


或者修改系統檔案/etc/ld.so.conf,這個檔案記錄了編譯時間使用的動態連結程式庫的路徑。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.