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

Rah*_*wal 5 c gcc libc

我正在尝试编译使用 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);
}
Run Code Online (Sandbox Code Playgroud)

我使用以下命令进行编译:--> 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
Run Code Online (Sandbox Code Playgroud)

google之后,由于我尝试静态编译,所以可以在lib目录下找到libdl.a。我也遇到了与 gethostbyname API 相同的问题.. 静态编译 dl_open 需要添加哪些其他库。

小智 0

一个可能的问题:

dlsym()
Run Code Online (Sandbox Code Playgroud)

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