Re: [問題] 共享函式庫的路徑?

看板LinuxDev作者 (松鼠)時間16年前 (2008/12/18 01:32), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《Xphenomenon (啦 )》之銘言: : 例如我想把某個函式庫 libtest.so 放在 /home/test/usr/lib 目錄下, : 我有一隻程式需要 link 到 libtest.so 函式庫,執行的時候會自動 : 去 /lib 下去找函式庫,可以指定路徑讓程式執行的時候去 /home/test/usr/lib 目錄下 : 找函式庫嗎? 方法有頗多種,一般有以下作法: (1) 設定 LD_LIBRARY_PATH 環境變數 (2) 將期望的搜尋動態函式庫路徑加入 /etc/ld.so.conf 並執行 ldconfig (3) 透過 linker 的 -rpath 選項,指定執行時期的搜尋函式庫路徑 以 (3) 來說,比方說有兩個 C 語言原始程式碼: $ cat test.c char *greeting() { return "Hello World!"; } $ $ cat main.c #include <stdio.h> char *greeting(); int main() { printf("string ==> %s\n", greeting()); return 0; } $ 對應的 Makefile 如下: $ cat Makefile all: gcc -o libtest.so -shared test.c gcc -o test main.c -L. -ltest clean: rm -f libtest.so test $ 編譯並執行: $ make && ./test ./test: error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory 出現錯誤訊息,因為找不到所需的 libtest.so,這時候只要在 gcc 中傳遞 linker options : -rpath,也就是修改為以下: gcc -o test main.c -Wl,-rpath $(PWD) -L. -ltest 如此一來,執行時期就會將 $(PWD),也就是建構 libtest.so 所在的目錄,列入搜尋, 於是重新編譯並執行: (假設目前目錄為 /tmp/rpath) $ make && ./test gcc -o libtest.so -shared test.c gcc -o test main.c -Wl,-rpath /tmp/rpath -L. -ltest string ==> Hello World! $ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.169.99.126

12/19 12:30, , 1F
謝謝大大的回答!:D
12/19 12:30, 1F
文章代碼(AID): #19IJURZ8 (LinuxDev)
討論串 (同標題文章)
文章代碼(AID): #19IJURZ8 (LinuxDev)