简体   繁体   中英

Linking shared library with libm

I have a program which is linked (dynamically) with libm. There are also several plugins for this program. Plugins are loaded explicitely with dlopen(). Some of these plugins use round() from libm.

On one system (Linux Mint 19.1 gcc 7.5.0) the program does not work because of unresolved round.

Here is simple example:

  1. Library (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)

     #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

     ./main c = 6.000000
  5. Run on Linux Mint 19.1, gcc 7.5.0

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

Now, add -lm for dll compilation

    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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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