gcc build links but shared library does not appear with ldd

左心房为你撑大大i 提交于 2019-12-07 00:57:14

问题


I've a program that I must build. The program depends on libA, and libA depends on libB. Both libs are in the same folder but ldd libA.so does not include libB.so so I must add it while linking it.

This is my gcc command:

gcc -L/path/to/libraries/lib -lA -lB -I/path/to/libraries/include main.cpp

The program builds and links, but it does not start. It gives me following error:

./a.out: symbol lookup error: /path/to/libraries/lib/libA.so: undefined symbol: symbol_used_in_libA_but_defined_in_libB

With ldd I can see that libB.so is not included in my binary:

linux-vdso.so.1 =>  (0x00007fffaecd9000)
libA.so => /path/to/libraries/lib/libA.so (0x00007effc02a4000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007effbfebb000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007effbfca5000)
/lib64/ld-linux-x86-64.so.2 (0x00007effc05cb000)

I have these conditions:

  • /path/to/libraries is inside LD_LIBRARY_PATH
  • running ldconfig is ok and ldconfig -p find both libA.so and libB.so
  • If in gcc command I change -lB with -lBB it gives me a linker error, so I think that gcc find correctly libB.so even if it does not link it inside the executable.

What I'm doing wrong? What I can do in order to link the executable to both libraries?


回答1:


Most Linux distributions (I assume you are using Linux based on the output of ldd) seem to configure gcc as to pass --as-needed to ld by default (e.g., see here for Debian). This means the final library/executable will only depend on a library (i.e., have a DT_NEEDED tag for that library) if some symbol of that library is actually used by the library/executable.

In your case, main.cpp does not use any functions of libB so the linker does not add libB as a dependency of the final executable. You can work around it by passing the --no-as-needed flag to the linker. E.g.,

gcc -Wl,--no-as-needed ...

Of course, the proper fix is to relink libA and make sure it lists libB as a dependency.



来源:https://stackoverflow.com/questions/28088100/gcc-build-links-but-shared-library-does-not-appear-with-ldd

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!