【发布时间】:2015-01-20 17:37:40
【问题描述】:
我有一个大型程序,可能会链接到一些外部库,但这些只是某些特定功能所需要的。但是,即使我不使用这些功能,仍然需要外部库。我可以做一些事情(最好在编译或链接时),以便仅在请求它们提供的功能时才需要这些库?
例子:
你好.c
#include <stdio.h>
#include <unistd.h>
extern const char *myfunc();
main() {
int z;
char buf[32];
z = gethostname(buf,sizeof buf);
if (strcmp(buf,"#!#!#!#!#") == 0) {
printf("%s\n", myfunc());
} else {
printf("%s\n", "No library used");
}
return 0;
}
shrobj.c:
const char *myfunc() {
return "Hello World";
}
编译为:
$ gcc -fpic -c shrobj.c
$ gcc -shared -o libshared.so shrobj.o
$ gcc hello.c -lshared -L.
$ ./a.out
./a.out: error while loading shared libraries: libshared.so: cannot open shared object file: No such file or directory
而我的主机名显然不是#!#!#!#!#:
$ LD_LIBRARY_PATH=. ./a.out
No library used
所以,我想要的是能够在没有库的情况下运行“./a.out”(无论出于何种原因,它可能不可用),只要它的函数没有被调用。
我已经看到可以使用dlopen() 获得延迟加载,但是,即使上面的示例是用 C 语言编写的,我的大部分代码也是用 fortran 编写的,尤其是可能调用库中函数的部分。
【问题讨论】:
-
你到底在问什么?是的,您可以使用
dlopen()延迟加载,直到您需要它时才需要该库... -
@ElliottFrisch 我在问是否可以通过其他不需要修改源代码的方式来完成
-
我不知道。