我正在尝试编译使用libdl库中的API的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int
main(int argc, char **argv)
{
void *handle;
double (*cosine)(double);
char *error;
handle = dlopen("libm.so", RTLD_LAZY);
if (!handle) {
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
dlerror(); /* Clear any existing error */
/* Writing: cosine = (double (*)(double)) dlsym(handle, "cos");
would seem more natural, but the C99 standard leaves
casting from "void *" to a function pointer undefined.
The assignment used below is the POSIX.1-2003 (Technical
Corrigendum 1) workaround; see the Rationale for the
POSIX specification of dlsym(). */
*(void **) (&cosine) = dlsym(handle, "cos");
if ((error = dlerror()) != NULL) {
fprintf(stderr, "%s\n", error);
exit(EXIT_FAILURE);
}
printf("%f\n", (*cosine)(2.0));
dlclose(handle);
exit(EXIT_SUCCESS);
}
我使用以下命令编译: - &GT; gcc -static -o foo foo.c -ldl
我收到以下错误:
foo.c:(.text+0x1a): warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
谷歌之后,因为我试图静态编译它,我可以在lib目录中找到libdl.a。我也遇到了与gethostbyname API相同的问题.. 为静态编译dl_open需要添加哪些其他库。
答案 0 :(得分:0)
一个可能的问题:
dlsym()
应在 main()中引用之前声明或实施。
答案 1 :(得分:0)
dlopen()仅适用于共享库。这意味着您无法静态链接它。你试过没有-static
吗?