简体   繁体   English

使用 libm 链接共享库

[英]Linking shared library with libm

I have a program which is linked (dynamically) with libm.我有一个与 libm 链接(动态)的程序。 There are also several plugins for this program.这个程序还有几个插件。 Plugins are loaded explicitely with dlopen().插件使用 dlopen() 显式加载。 Some of these plugins use round() from libm.其中一些插件使用 libm 中的 round()。

On one system (Linux Mint 19.1 gcc 7.5.0) the program does not work because of unresolved round.在一个系统(Linux Mint 19.1 gcc 7.5.0)上,由于未解决的回合,程序无法运行。

Here is simple example:这是一个简单的例子:

  1. Library (lib.c)图书馆 (lib.c)

     #include <stdio.h> #include <math.h> void func(double a, double b) { double c; c = round(a + b); printf("c = %lf\\n", c); }
  2. Main program (main.c)主程序(main.c)

     #include <stdio.h> #include <dlfcn.h> void *dll; void (*f)(double, double); double a = 1.234, b = 4.321; int main(void) { dll = dlopen("./lib.so", RTLD_LAZY); f = dlsym(dll, "func"); f(a,b); return 0; }
  3. Building (Makefile)构建(生成文件)

     all: gcc -Wall -Os -shared -fPIC lib.c -o lib.so gcc -Wall -Os -rdynamic -fPIC main.c -o main -ldl -lm
  4. Run on Debian 8, gcc 4.9.2在 Debian 8、gcc 4.9.2 上运行

     ./main c = 6.000000
  5. Run on Linux Mint 19.1, gcc 7.5.0在 Linux Mint 19.1、gcc 7.5.0 上运行

     ./main ./main: symbol lookup error: ./lib.so: undefined symbol: round

Now, add -lm for dll compilation现在,添加 -lm 进行 dll 编译

    gcc -Wall -Os -shared -fPIC lib.c -o lib.so -lm

     ./main 
    c = 6.000000

So, the question is - why on this particular system one must use -lm not only for main program but for plugin also?所以,问题是 - 为什么在这个特定的系统上,不仅必须将 -lm 用于主程序,还必须用于插件?

Just like an executable program, shared libraries are linked entities (unlike static libraries which are archives of object files).就像可执行程序一样,共享库是链接实体(与作为目标文件存档的静态库不同)。

Since shared libraries are linked like executables, you also need to link with the libraries that your library depends on:由于共享库像可执行文件一样链接,因此您还需要链接库所依赖的库:

gcc -Wall -Os -shared -fPIC lib.c -o lib.so -lm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM