作者jserv (松鼠)
看板LinuxDev
标题Re: [问题] 共享函式库的路径?
时间Thu Dec 18 01:32:10 2008
※ 引述《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
1F:推 Xphenomenon:谢谢大大的回答!:D 12/19 12:30