【问题标题】:Dynamic Linking in C (lib*.so) libraryC (lib*.so) 库中的动态链接
【发布时间】:2010-10-02 13:03:31
【问题描述】:

我已经编写了一个代码,其中包含一个 可执行文件 和 [lib*.so] 库作为我的参数并链接 @Run-time。

我还想在 (*.o) 文件@run-time 中获取函数并链接它。 但我不知道该怎么做。

编辑 1: 我试图链接的函数是 lib*.so 库中 .o 文件的一部分。 所以我想指定库名以及在同一库@Run-Time 中的函数名。

例如。如果我的库包含两个函数(即 *.o 文件),则链接器应编译我要使用的函数 @Run-Time。

我已经发布了代码,请帮助:

#include <stdio.h>
#include <unistd.h>
#include <dlfcn.h>    // use -ldl

typedef float (*DepFn)(short, short);

int main(int argc, char* argv[])
{
    void* lib;
    DepFn df;

    if(argc < 2)
        return printf("USAGE: %s lib-file\n", argv[0]);

    lib = dlopen(argv[1], RTLD_NOW);
    if(lib == NULL)
        return printf("ERROR: Cannot load library\n");

    df = dlsym(lib, "Depreciation");
    if(df)
    {
        short l, i;

        printf("Enter useful-life of asset: ");
        scanf("%hd", &l);

        for(i = 1; i <= l; i++)
        {
            float d = 100 * df(l, i);
            printf("%hd\t%.1f%%\n", i, d);
        }
    }
    else
        printf("ERROR: Invalid library\n");

    dlclose(lib);
}

【问题讨论】:

  • 代码看起来还不错,那么实际发生了什么?什么不工作?你是如何编译和链接你的 libXXX.so 的?
  • @nos -- 这工作正常。但我想知道如何在编译时也接受一个函数。

标签: c unix linker posix dynamic-linking


【解决方案1】:

如果你需要在运行时获取函数名,你需要在 argv[2] 中传递它,而不是在 dlsym 中硬编码函数名使用 argv[2]。

if(argc < 3)
        return printf("USAGE: %s lib-file function-name\n", argv[0]);

    lib = dlopen(argv[1], RTLD_NOW);
    if(lib == NULL)
        return printf("ERROR: Cannot load library\n");

    df = dlsym(lib, argv[2]);

【讨论】:

    【解决方案2】:

    您无法在运行时使用标准函数加载可重定位 (*.o)。您需要确保将对象编译为与位置无关的代码(例如-fPIC),然后从中创建一个共享对象。像ld -shared -o foo.so foo.o 这样的东西可能会成功。

    【讨论】:

      【解决方案3】:

      根据您的 cmets,您只想链接到您的共享库,

      将您的代码更改为:

      extern float Depreciation(short i,k); //should rather go in a header file
      
      int main(int argc, char* argv[])
      {
          short l, i;
      
              printf("Enter useful-life of asset: ");
              scanf("%hd", &l);
      
              for(i = 1; i <= l; i++)
              {
                  float d = 100 * Depreciation(l, i);
                  printf("%hd\t%.1f%%\n", i, d);
              }
          }
      

      编译并链接到您的共享库:

       gcc -o myprogram myprogram.c -lXX
      

      您的 libXX.so 需要安装在例如/usr/lib/ 上面的工作 请参阅here 了解更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-16
        • 2011-01-11
        • 1970-01-01
        • 1970-01-01
        • 2014-02-14
        • 1970-01-01
        • 1970-01-01
        • 2012-12-31
        相关资源
        最近更新 更多