Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
720 views
in Technique[技术] by (71.8m points)

linker - gcc build links but shared library does not appear with ldd

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...