[英]C program linking with shared library without setting LD_LIBRARY_PATH
我正在閱讀GCC簡介,它說如果一個軟件包同時包含.a和.so。 gcc更喜歡共享庫。 默認情況下,加載程序僅在預定義的一組系統目錄中搜索共享庫,例如/usr/local/lib
和/usr/lib
。 如果庫不在其中一個目錄中,則必須將其添加到加載路徑,或者您需要使用-static
選項強制它使用.a庫。 但是,我嘗試了以下方法:
vim hello.c:
#include <gmp.h>
#include <stdio.h>
int main() {
mpz_t x;
mpz_init(x);
return 0;
}
gcc hello.c -I/opt/include -L/opt/lib -lgmp (my gmp library is in opt)
./a.out
它運行。 該書說它應該有以下錯誤:
./a.out: error while loading shared libraries:
libgdbm.so.3: cannot open shared object file:
No such file or directory
(好吧,這本書以GDBM為例,但我使用的是GMP,但這沒關系嗎?)
但是,我沒有設置LD_LIBRARY_PATH=/opt/lib
,你可以看到我也沒有使用-static
選項,但a.out
仍然運行。
你能告訴我為什么,並告訴我如何得到書中描述的錯誤? 是的我想要錯誤,所以我會理解我誤解的內容。
從您對我的評論的回復:
linux-gate.so.1 => (0xb7746000)
libgmp.so.10 => /usr/lib/i386-linux-gnu/libgmp.so.10 (0xb76c5000)
libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xb7520000)
/lib/ld-linux.so.2 (0xb7747000)
所以,你的程序正在從/usr/lib
。
您可以嘗試做的是重命名/opt/lib
,並鏈接新名稱。
mv /opt/lib/libgmp.so /opt/lib/libgmp-test.so
gcc hello.c -I/opt/include -L/opt/lib -lgmp-test
然后嘗試運行該程序。 另外,將ldd
與新a.out
的結果與之前的結果進行比較。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.