I've read this link and I can understand what it says.

As it shows in this image, I have a question about the dynamic libraries.
Saying that I've coded a C++ program. As my understanding, when I use some compiler, such as gcc to compile my program (for example, g++ main.cpp), it is about doing the job of the step 3 and the step 4, which means that it is only about compiling and linking static libraries.
However, as we all know, we can append -lXXX or -LXXX to g++ to tell it where the necessary dynamic libraries are. As my understanding, this is about the step 5 in this image.
So now I'm confused. If the command g++ is doing the job about compiling and linking static libraries, why can we and should we give it the dynamic libraries? (if not there gonna be some undefined reference errors)
Is the dynamic library necessary while compiling and linking? If so, why does this image tell us that the step 5 is the part of run, instead of the part of build?
Lets say you main program called one library function F1(), that could be either in a static library or a dynamic library.
If its in a static library, that library will be loaded at compile/link time and the address of F1() can be fixed (relative to program start address). When you run the program the loader does not need to look for the library - already part of the exe.
If F1() is in a dynamic library, the compiler may not know the size of either F1() or any of its sub-dependencies. (It knows only their signatures via the .h files). When you run the program, the exe can "advise" the loader that it also needs to load the dynamic library. The final linking is then done at load-time, when the loader has access to the full information about the exe and its libraries and can do its "dynamic linking" job.
Should also point out that the dynamic/shared library may already be in memory by another user. In this case the final resolution of addresses (where in memory F1() actually exists) cannot be done until load time.
In any case, the compiler/linker needs to know if the library is static or dynamic/shared.
The exact process in Gcc or other compiler may differ from this simple explanation, but the reason why the compiler/linker needs to know if the libraries are static or dynamic should be clear.
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