Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc -L command confusion

Tags:

c++

gcc

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?

like image 358
Mars Avatar asked Sep 05 '25 01:09

Mars


1 Answers

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:

  • it is not necessary that 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.)
  • it may be unsafe, so ld.so ususally seeks over list of "trusted" paths where non-root users couldn't write

However, there were some cases when saving -L would be useful (i.e. software installed into /opt) , so some of Unixes introduced RPATH.

like image 133
myaut Avatar answered Sep 07 '25 19:09

myaut