Why we need the presence of the shared library during the compile time of my executable? My reasoning is that since shared library is not included into my executable and is load
gcc -o main main.c -L. -lfoo
This command does (at least) two steps: compile main.c
into an object file and link all resources into an executable main
. The error you see is from the last step, the linker.
The linker is responsible for generating the final executable machine code. It requires the shared object library because it needs to generate the machine code which loads it and executes any functions used in it.
Nothing is needed at compile time, because C has a notion of separate compilation of translation units. But once all the different sources have been compiled, it is time to link everything together. The notion of shared library is not present in the standard but is it now a common thing, so here is how a common linker proceeds:
This produces the executable file. Then at load time, the dynamic loader knows all the dynamic modules that are required and loads them in memory (if they are not already there) along with the actual executable and builds a (virtual) memory map