I have a large program that may be linked against some external libraries, but these are only needed for some specific functions. However, even if I don't use these functions, the external libraries are still required. Can I do something (preferably at compile or link time) so that the libraries are only required if the functionality they provide is requested?
Example:
hello.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";
}
Compiled as:
$ 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
and my hostname is obviously not #!#!#!#!#
:
$ LD_LIBRARY_PATH=. ./a.out
No library used
So, what I want is being able to run "./a.out" without the library (which for whatever reason may be unavailable), as long as its function is not called.
I've seen that delayed loading can be obtained with dlopen()
but, even though the above example is in C, most of my code is in fortran, and in particular the part that might call the functions in the library.