首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用静态库libdl.a编译程序

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

Stack Overflow用户
提问于 2016-04-07 17:46:34
回答 2查看 4.1K关注 0票数 5

我正在尝试编译使用libdl库中的API的示例代码:

代码语言:javascript
复制
#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

我得到了以下错误:

代码语言:javascript
复制
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,还需要添加哪些其他库。

EN

回答 2

Stack Overflow用户

发布于 2016-04-07 17:50:01

一个可能的问题是:

代码语言:javascript
复制
dlsym()

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

票数 0
EN

Stack Overflow用户

发布于 2016-06-01 20:17:52

dlopen()只适用于共享库。这意味着你不能静态地链接它。你在没有-static的情况下尝试过吗?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36472442

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档