I am trying to understand static linking,dynamic linking,shared libraries,static libraries etc, with gcc. Everytime I try to delve into this topic, I have something which I don't quite understand.
So I have created a shared library. Now I want to link this shared library with my main program to create an executable.
gcc -Wall -L. main.c -lcgreet -o greet
It very well works and if I set the LD_LIBRARY_PATH before running greet( or link it with rpath option) I can make it work.
My question is however different: Since I am anyway using shared library, is it not possible to force symbol resolution at runtime (not sure about the terminology but perhaps called dynamic linking as per the book "Linkers and Loaders"). I understand that we may not want to do it because this makes the program run slow and has overhead everytime we want to run the program, but I am trying to understand this to clear my concepts.
Does gcc linker provide any option to delay symbol resolution at runtime? (to do it with the library we are actually going to run the program with)(as library available at compile time may be different than the one available at runtime if any changes in the library) I want to be able to do sth like: gcc main.c -I. (what option needed here?) so that I don't have to give the library name, and just tell it that I want to do symbol resolution at runtime, so headers are good enough for now, actual library names are not needed.
Linking to a shared library does delay symbol resolution until runtime. You can verify this by changing your shared library to say "Good bye, cruel world." and rebuilding the library without rebuilding your executable. The "greet" executable, which has not changed, will output "Good by, cruel world." The link phase just ensures that you've got all the symbols accounted for by the libraries you are listing as dependencies.
If you want to go further with proving this fact, create a new library that implements just one of the functions, then use LD_PRELOAD to load that library and replace the function your re-implemented.