Question

I have a limited knowledge of dynamic libraries and I usually have problems related to libraries that I do not understand. I recently learned of libraries from google search and especially from the following links:

If I understood well (correct me if I am wrong), there are two possible usages of shared objects:

  • dynamic linking: the shared object is automatically loaded by the dynamic linker when the program starts.

  • dynamic loading: the share object is loaded and used under the program control at runtime through the dynamic loading API (dlopen, dlerror, dlsym and dlclose). That option is useful for plugins.

If I got everything right, in the case of dynamic linking, all the symbols are verified at compilation time. This allows the compiler/linker to know exactly which shared object is effectively used by the program and which one is not used.

Now, it happens that the dynamic linker is always invoked at runtime even if the shared object is not used. It can be verified by linking an empty program against libraries that are not in locations searchable at runtime, and the execution will fail. Linking a program against library that is not actually used in the program can happen when there are updates and the use of a library is no longer necessary. It also happen when one isolates a part of the program for debugging, and link against all the libraries of the main program.

My question is: is there an option to ask the compiler/linker to not include reference to shared objects that do not have symbols referred to in the program? Is there any issue that prevent the compiler from doing that?

The following posts share some similarities with the present question, but none of them has an accepted answer, nor an answer that satisfies my curiosity:

Was it helpful?

Solution

If you happen to use g++/ld there are a few suggestions spelled out on How to remove unused C/C++ symbols with GCC and ld?

For example:

  • gcc -Os -fdata-sections -ffunction-sections test.cpp -o test.o -Wl,--gc-sections
  • -dead_strip
  • -dead_strip_dylibs

However I'm actually not sure it's possible for the compiler to do this in the general case. Consider a dependent shared library that has a weak reference to the library that you want to remove from your link line: How would the compiler know that it's safe to remove the library and/or symbols at that point?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top