I was working with SFML, I compiled a little test program and added the linkage option -lsfml-audio
. Then, I used ldd ./program
to see the dynamic libraries it was linking to. Surprisingly, there were a lot, none of them had I manually selected in my makefile, nor using pkg-config --libs
.
I started reading about shared libraries, and made a little example to solve my doubts. However, I have this question:
why some libraries need you to add the dependencies in your makefile (either manually or using a script like
pkg-config
) and other libraries automatically link their dependencies?
When you're creating your dynamic library, is just as easy as adding the proper -ldependency
options in the g++ -shared ...
command to avoid the user the hassle of manually adding the dependencies later on. Why many of the available libraries don't do that?
I guess it must be related to the ability of fine tuning which libraries get linked and such.
However, most shared library systems are restricted in that they only allow a single level of dependencies. In these systems, programs may depend on shared libraries, but shared libraries may not depend on other shared libraries.
Shared libraries (also called dynamic libraries) are linked into the program in two stages. First, during compile time, the linker verifies that all the symbols (again, functions, variables and the like) required by the program, are either linked into the program, or in one of its shared libraries.
What are Shared Libraries in C? Shared libraries are libraries that use dynamic linking vs static linking in the compilation steps for compiling a file. Static and dynamic linking are two processes of collecting and combining multiple object files in order to create a single executable file.
The libraries are physically loaded into the computer's memory instead and during the linking stage of compilation, only the address in the memory of the library function is added in the final executable file. The physical code itself is located at that address.
Shared libraries will generally link in their dependencies. However, static libraries are not capable of doing so. pkg-config --libs
often includes all dependencies (direct and indirect) so that you can switch to static compilation by simply adding -static
without having to add additional library dependencies as well.
Note that these excess direct dependencies are considered unwanted in some cases (eg, debian tries to avoid them in packaged binaries, as they make library soname transitions more traumatic than necessary). You can instruct the linker to strip direct dependencies from the final executable that aren't needed with the -Wl,--as-needed
flag.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With