我正在尝试编译使用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);
}我使用如下命令编译:--> -static -o 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在google之后,因为我试图静态编译它,所以我可以在lib目录中找到libdl.a。我在使用gethostbyname API时也遇到了同样的问题。要静态编译dl_open,还需要添加哪些其他库。
发布于 2016-04-07 17:50:01
一个可能的问题是:
dlsym()应该在main()中引用它之前声明或实现它。
发布于 2016-06-01 20:17:52
dlopen()只适用于共享库。这意味着你不能静态地链接它。你在没有-static的情况下尝试过吗?
https://stackoverflow.com/questions/36472442
复制相似问题