使用共享库文件编译驱动程序时未定义的引用

使用共享库文件编译驱动程序时未定义的引用

我制作了一个简单的内存管理器,并尝试使用驱动程序中的共享库来编译它。

共享库文件本身编译得很好。但是,当我通过使用内存管理器调用共享库中的函数来编译驱动程序时,它显示了下面的屏幕截图:错误信息

这是我的shared.c代码

/* conveniences for casting and declarations */
typedef block_info* (*MM_CREATE)(size_t, MMPolicy);
typedef void* (*MM_ALLOCATE)(block_info *, size_t, char *);
typedef int (*MM_DEALLOCATE)(block_info *, void *);
typedef void (*MM_DESTROY)(block_info *);

/* Function pointers retrieved from the shared library */
typedef struct LibraryFunctions
{
   MM_CREATE create;
   MM_DESTROY destroy;
   MM_ALLOCATE allocate;
   MM_DEALLOCATE deallocate;
}LibraryFunctions;

/* Loads a shared library and returns a pointer to it in libhandle */

/* Returns SUCCESS, if it successful, otherwise, FAILURE           */
int load_library(const char *libname, void **libhandle)
{

*libhandle = dlopen(*libhandle, RTLD_LAZY);

if(!(*libhandle))
{
    return FAILURE;
}
else
{
    return SUCCESS;
}

return *libname;
}
int get_functions(void *libhandle, 
               LibraryFunctions *functions, 
               const char **fn_names)
{
functions->create = (MM_CREATE)(intptr_t)dlsym(libhandle, *fn_names);

if(!functions->create)
{
    return FAILURE;
}

functions->destroy = (MM_DESTROY)(intptr_t)dlsym(libhandle, *fn_names);

if(!functions->destroy)
{
    return FAILURE;
}

functions->allocate = (MM_ALLOCATE)(intptr_t)dlsym(libhandle, *fn_names);

if(!functions->allocate)
{
    return FAILURE;
}

functions->deallocate = (MM_DEALLOCATE)(intptr_t)dlsym(libhandle, *fn_names);

if(!functions->deallocate)
{
    return FAILURE;
}

return SUCCESS;

这是调用共享库的驱动程序代码的一部分:

void setup(void)
{
  const char *fn_names[] = {"mm_create", "mm_destroy", "mm_allocate",   "mm_deallocate"};
  LibraryFunctions funs;
  int error;

  error = load_library("./libmemmgr.so", &gLib);
  if (error == FAILURE)
  {
    printf("load_library failed! %s\n", dlerror());
    exit(-1);
  }

  error = get_functions(gLib, &funs, fn_names);
  if (error == FAILURE)
  {
    printf("get_functions failed! %s\n", dlerror());
    exit(-1);
  }

  mmlib_create = funs.create;
  mmlib_destroy = funs.destroy;
  mmlib_allocate = funs.allocate;
  mmlib_deallocate = funs.deallocate;

}

void teardown(void)
{
  dlclose(gLib);
}

我不确定是什么导致了错误。

编辑:所以我设法运行exe文件,但在“get_functions”上失败。我的 get_functions 有问题吗?

答案1

您似乎没有链接到定义了和的dl库(至少在 Linux 上)。dlclosedlerror

您也没有链接到您自己定义 function 的共享库load_library。您根本没有显示定义的代码get_functions,所以我不确定它位于哪里。

所以:你的共享库应该命名为libfoo.so,并且你需要-L. -lfoo -ldl在所有文件之后添加到编译器命令行中.c。会-L.告诉编译器将当前目录添加到库搜索路径中,会告诉它从当前目录-lfoo链接到,并且会告诉它还链接到库搜索路径中的其他位置(可能是 /usr /lib)。libfoo.so-ldllibdl.so

相关内容