c - 动态库动态附加

标签 c linux makefile

EDIT 发现了一个问题,但它仍然需要解决它应该在下面的答案中 我的任务是根据现有文件编写应用程序。 test.c(main) randapi.c randapi.h(这里有 2 个函数)和 initapi.c(一个函数)。 “你怎么能使用动态库作为动态加载库。使用 eg9(我创建了一个动态库并且它工作正常)编写应用程序,这个库将被动态附加”

这是我对 makefile 的尝试,但终端显示:当我使用 ./program 运行文件时无法打开

我也试过没有附加 initapi.c 的版本,但它说 initRand 是未知的,除了 make 文件明确附加它

#include <stdio.h>
#include <dlfcn.h>
#include <stdlib.h>
#define ITERATIONS  1000000L

int main(int argc, char** argv)
{
  long  i;
  long  isum;
  float fsum;
  void *lib;

  lib=dlopen("librandapi.so", RTLD_LAZY); 
  if (!lib)
  {
    printf("failed to open");
    exit(1);
  }
  int (*getRand)(int);
  float (*getSRand)();
  void (*initRand)();

getRand=dlsym(lib,"getRand");
getSRand=dlsym(lib,"getSRand");
initRand=dlsym(lib,"initRand");

  initRand();
  isum = 0L;
  for (i = 0 ; i < ITERATIONS ; i++) {
    isum += ((*getRand)(10));
  }
  printf( "getRand() Average %d\n", (int)(isum / ITERATIONS) );

  fsum = 0.0;
  for (i = 0 ; i < ITERATIONS ; i++) {
    fsum += ((*getSRand)());
  }

  printf( "getSRand() Average %f\n", (fsum / (float)ITERATIONS) );
  dlclose(lib);
  return 0;
}
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
makefile

  zad9: test.c
    gcc -Wall -o zad9 test.c -ldl
librandapi.so: randapi.o initapi.o
    gcc -shared -o librandapi.so randapi.o initapi.o
randapi.o: randapi.c randapi.h
    gcc -c -Wall -fPIC randapi.c
initapi.o: initapi.c
    gcc -c -Wall -fPIC initapi.c

//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////

   zad9: test.c initapi.c
    gcc -Wall -o zad9 test.c initapi.c -ldl
librandapi.so: randapi.o initapi.o
    gcc -shared -o librandapi.so randapi.o 
randapi.o: randapi.c randapi.h
    gcc -c -Wall -fPIC randapi.c

最佳答案

查看 man 3 dlopen 中的这一行:

If filename contains a slash ("/"), then it is interpreted as a (relative or absolute) path‐name. Otherwise, the dynamic linker searches for the object as follows (see ld.so(8) for further details):

(然后是一系列规则,既不包括当前目录,也不包括可执行文件所在的目录)。

我的猜测是您正在将 librandapi.so 复制到当前目录,这就是 dlopen() 找不到它的原因。

如果是这种情况,解决方案很简单:

lib=dlopen("./librandapi.so", RTLD_LAZY);

关于c - 动态库动态附加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33695554/

相关文章:

java - crc 四个字节将 C 代码转换为 Java 产生意外结果

C - 公制转换字符串

linux - awk 从 mtjoseph :6/MKTCzMS/YU. 中提取 "Matthew":10974:10060:Matthew

c - 对 `UNITY_BEGIN' 和 'UNITY_END' 的 undefined reference

c++ - 导致 vtable 错误的 Makefile 设置

c - 为什么使用指针到指针会出现内存访问冲突错误

C 字符与返回键不匹配\n

linux - 在哪里找到卸载文件

linux - 使用 sed 替换最后一次出现

c++ - 如何为 C 和 C++ 创建一个 makefile,源代码在子目录中