Shared-Library

使用共享庫文件編譯驅動程序時未定義的引用

  • July 9, 2015

我做了一個簡單的記憶體管理器,我正在嘗試使用驅動程序中的共享庫來編譯它。

共享庫文件本身編譯得很好。但是,當我通過使用記憶體管理器呼叫共享庫中的函式來編譯驅動程序時,它顯示了下面的螢幕截圖:錯誤資訊

這是我的 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 有什麼問題嗎?

您似乎沒有連結到定義和定義的dl庫(至少在 Linux 上)。dlclose``dlerror

您也沒有連結到您自己的共享庫,您在其中定義了 function load_library。您根本沒有顯示定義的程式碼get_functions,所以我不確定它在哪裡。

所以:您的共享庫應該命名為libfoo.so,並且您需要在所有文件-L. -lfoo -ldl之後添加到編譯器命令行。.c-L.告訴編譯器將目前目錄添加到庫搜尋路徑中,-lfoo將告訴它libfoo.so從目前目錄連結到 ,並且-ldl將告訴它也連結libdl.so到庫搜尋路徑中的其他位置(可能是 /usr /lib)。

引用自:https://unix.stackexchange.com/questions/214984