问题
I have a question which may be somewhat silly because I'm pretty sure I may know the answer already.
Suppose you have static library A, and dynamic shared object library B and your program C under linux. Suppose that library A calls functions from library B and your program calls functions from library A. Now suppose that all functions that C calls in A make no use of functions in B.
To compile C will it be enough to link just A and omit B and furthermore can your program C be run on a system without library B installed?
回答1:
If your program calls functions in A that don't reference B then B is not required either at link or load time, assuming that the functions in A are in separate compilation units, which is usually the case for a library.
The linker will pull the functions from the library that C uses and since none of them call functions in B, B will not be needed.
回答2:
Holy placeholder name overload, batman. Let's first replace A, B, and C, with libstatic, libshared, and myapp to make things a little more legible:
Suppose you have static library
libstatic, and dynamic shared object librarylibsharedand your programmyappunder linux. Suppose that librarylibstaticcalls functions from librarylibsharedand your program (myapp) calls functions from librarylibstatic. Now suppose that all functions thatmyappcalls inlibstaticmake no use of functions inlibshared.To compile
myappwill it be enough to link justlibstaticand omitlibsharedand furthermore can your programmyappbe run on a system without librarylibsharedinstalled?
So the way I understand your question, there is a library libstatic, some functions in which make use of libshared. You want to know: if I don't use any of the libstatic functions that are dependent on libshared, will myapp link and run without libshared?
The answer is yes, so long as two things are true:
The calls you make into
libstaticdo not depend onlibshareddirectly or indirectly. Meaning that ifmyappcalls a function inlibstaticwhich calls another function inlibstaticwhich calls a function inlibshared, thenmyappis now dependent onlibshared.The calls you make into
libstaticdo not depend on any function inlibstaticwhose implementation appears in the same compilation unit (object file) with a call tolibshared. The linker brings in code from the static library at the level of object files, not at the level of individual functions. And remember, this dependency is similarly chained, so if you call a function infoo.o, and something else infoo.ocalls a function inbar.o, and something inbar.odepends onlibshared, you're toast.
When you link in a static library into an application, only the object files that contain the symbols used (directly or indirectly) are linked. So if it turns out that none of the object files that myapp ends up needing from libstatic depend on libshared, then myapp doesn't depend on libshared.
来源:https://stackoverflow.com/questions/2631558/extraneous-library-linkage