如何使用静态库libdl.a编译程序?

时间:2022-03-14 15:30:43

I am trying to compile the example code which is using APIs from libdl library:

我正在尝试编译使用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);
}

I used the following command to compile: --> gcc -static -o foo foo.c -ldl

我使用下面的命令来编译:-> gcc -static -o foo foo。c的低密度脂蛋白

I got the following error:

我有以下错误:

foo.c:(.text+0x1a): warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking

After google, since I am trying to compile it statically, I can find the libdl.a in the lib directory. I am getting the same issue with gethostbyname API also.. What are the other libraries needs to add to compile dl_open statically.

在谷歌之后,由于我试图静态地编译它,我可以找到libdl。在lib目录中。我也得到了gethostbyname API的相同问题。其他的库需要添加什么以静态地编译dl_open。

2 个解决方案

#1


0  

One possible problem:

一个可能的问题:

dlsym()

Should be declared or implemented before it is referenced in main().

在main()中引用之前应该声明或实现。

#2


0  

dlopen() works only with shared libs. That means that you can't link it statically. Have you tried without -static ?

dlopen()只适用于共享的libs。这意味着你不能静态地链接它。你试过没有静电吗?

#1


0  

One possible problem:

一个可能的问题:

dlsym()

Should be declared or implemented before it is referenced in main().

在main()中引用之前应该声明或实现。

#2


0  

dlopen() works only with shared libs. That means that you can't link it statically. Have you tried without -static ?

dlopen()只适用于共享的libs。这意味着你不能静态地链接它。你试过没有静电吗?