Reputation: 4995
Let's say I have a shared library file, libdemo.so
, where libdemo.so
is the final linker.
If I want to build the executable, and if the library file is in the current working directory, I link it in with the -L. -ldemo
flags.
But when I run the executable, unless I specify the library path, LD_LIBRARY_PATH=.
, the executable can't find the link. So why the need for the extra LD_LIBRARY_PATH
setting? The flags are for the link-time library path and the environment variable is the run-time library path supposedly.
Alternatively, if I build the executable and specify a run-time library path using -Wl,-rpath,.
I can omit -L. -ldemo
.
I know this has to do with link-time and run-time but I am unclear on what the difference is. For instance, when not using -rpath
, what does the -L. -ldemo
actually do if the executable needs LD_LIBRARY_PATH
to find the library file? And when using the latter method, if specifying -rpath
means copying the directory location into the run-time library path, why does this also allow the -L. -ldemo
to be omitted?
If the link-time library path and run-time library path are different, how come the latter method doesn't need the link-time library path when building? What is the difference between a link-time library path and run-time library path?
Upvotes: 4
Views: 1350
Reputation: 4995
After some research (reading a textbook), I found the answer I was looking for.
Basically, since the executable file no longer contains copies of the object files, it needs some way to identify the shared library that it needs. During the link phase, the name of the shared library is embedded in the executable, but the specific location is not yet specified. So the -L. -ldemo
is really just to provide the name of the library file. Note that in the question, I say that -L. -ldemo
was not specified when setting the -rpath
. That is because in that command I had actually passed the name of the library directly, libdemo.so
. If I had not done so specifying it with -L. -ldemo
was necessary.
The run-time library path is subsequently provided to specify the exact location at the time of execution.
Upvotes: 0
Reputation: 11504
Because linking is done by two different instances of Linker.
When you compile & link your program, linker like /usr/bin/ld
checks external references and builds your executable adding external reference libdemo.so
.
When you run your program, run-time linker /lib64/ld-linux-x86-64.so.2
(or generally say ld.so
) loads all needed shared objects. There are several reasons -L
is not saved:
libdemo.so
is located at the same path it was during compiling (because you could copy your binary onto another host, that path was internal build path, etc.)ld.so
ususally seeks over list of "trusted" paths where non-root users couldn't writeHowever, there were some cases when saving -L
would be useful (i.e. software installed into /opt
) , so some of Unixes introduced RPATH.
Upvotes: 3