为没有.so文件的共享库构建

时间:2022-01-23 06:30:16

I'm compiling C source which calls a shared library, and have only the library header on the build machine, not the .so file (different cpu architecture). How do I make the code find and load /usr/lib/libx.so at runtime?

我正在编译调用共享库的C源代码,并且在构建机器上只有库头,而不是.so文件(不同的cpu架构)。如何在运行时查找代码并加载/usr/lib/libx.so?

2 个解决方案

#1


1  

REVISED from original suggestion of LD_LIBRARY_PATH.

从LD_LIBRARY_PATH的原始建议中修改。

Assuming you are on a linux system, shared libraries may be loaded before execution starts via the LD_PRELOAD environment variable:

假设您使用的是Linux系统,可以在执行启动之前通过LD_PRELOAD环境变量加载共享库:

$ LD_PRELOAD="/usr/lib/libx.so" your_app

However, linking with -Wl,--unresolved-symbols=ignore-in-object-files is probably not a good practice. I'd recommend using dlsym to load arbitrary symbols from a dynamic library. For example,

但是,链接-Wl, - unresolved-symbols = ignore-in-object-files可能不是一个好习惯。我建议使用dlsym从动态库加载任意符号。例如,

#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>

int main ()
{
   void *handle;
   void (*foo_fp) (void);  // function signature from dynamic library

   // Dynamically load libfoo.so, searching it from LD_LIBRARY_PATH
   handle = dlopen ("libfoo.so", RTLD_LAZY);

   // Load function 'foo' from libfoo.so
   foo_fp = dlsym(handle, "foo");

   // Calls 'foo' from libfoo.so
   foo_fp();
   return 0;
}

To compile this:

编译这个:

gcc -o main main.c -ldl

To execute:

执行:

export LD_LIBRARY_PATH=<location of libfoo.so>
./main

#2


1  

Create a 'dummy' libx.so file that exports the needed symbols.

创建一个“虚拟”libx.so文件,用于导出所需的符号。

#1


1  

REVISED from original suggestion of LD_LIBRARY_PATH.

从LD_LIBRARY_PATH的原始建议中修改。

Assuming you are on a linux system, shared libraries may be loaded before execution starts via the LD_PRELOAD environment variable:

假设您使用的是Linux系统,可以在执行启动之前通过LD_PRELOAD环境变量加载共享库:

$ LD_PRELOAD="/usr/lib/libx.so" your_app

However, linking with -Wl,--unresolved-symbols=ignore-in-object-files is probably not a good practice. I'd recommend using dlsym to load arbitrary symbols from a dynamic library. For example,

但是,链接-Wl, - unresolved-symbols = ignore-in-object-files可能不是一个好习惯。我建议使用dlsym从动态库加载任意符号。例如,

#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>

int main ()
{
   void *handle;
   void (*foo_fp) (void);  // function signature from dynamic library

   // Dynamically load libfoo.so, searching it from LD_LIBRARY_PATH
   handle = dlopen ("libfoo.so", RTLD_LAZY);

   // Load function 'foo' from libfoo.so
   foo_fp = dlsym(handle, "foo");

   // Calls 'foo' from libfoo.so
   foo_fp();
   return 0;
}

To compile this:

编译这个:

gcc -o main main.c -ldl

To execute:

执行:

export LD_LIBRARY_PATH=<location of libfoo.so>
./main

#2


1  

Create a 'dummy' libx.so file that exports the needed symbols.

创建一个“虚拟”libx.so文件,用于导出所需的符号。