115

The GNU Compiler Collection (aka gcc) and ld provide many ways to specify a search path for libraries—among them the -rpath and -L flags. The manpages reveal no differences between these two flags, effectively saying each flag adds a library to the library search path. Yet it seems strange that both flags do exactly the same thing. What are the differences, if any, between these two options?

Braiam
  • 1
  • 11
  • 47
  • 78
Craig M. Brandenburg
  • 3,354
  • 5
  • 25
  • 37

1 Answers1

142

You must be reading some outdated copies of the manpages (emphasis added):

-rpath=dir
      Add a directory to the runtime library search path. This is used
      when linking an ELF executable with shared objects. All -rpath
      arguments are concatenated and passed to the runtime linker, which
      uses them to locate shared objects at runtime.

vs.

-L searchdir
--library-path=searchdir
      Add path searchdir to the list of paths that ld will search for
      archive libraries and ld control scripts.

So, -L tells ld where to look for libraries to link against when linking. You use this (for example) when you're building against libraries in your build tree, which will be put in the normal system library paths by make install. --rpath, on the other hand, stores that path inside the executable, so that the runtime dynamic linker can find the libraries. You use this when your libraries are outside the system library search path.

derobert
  • 49,731
  • 15
  • 94
  • 124
  • 22
    Notes: 1. Most of the time when one needs `-rpath=/some/weird/path`, one needs `-L /some/weird/path` too. 2. With `gcc` one needs use `-Wl,-rpath=dir`. – n. m. could be an AI Sep 24 '14 at 14:06
  • 5
    I still don't understand why both are needed. I have the same experience as n.m. above. What information is needed from the library at build time? Apart from possible h-files, of cause. But that's another thing I guess... – Fredrik Johansson Jan 22 '15 at 17:39
  • 1
    @FredrikJohansson That'd be a reasonable subject for a new question (presuming it hasn't already been asked, of course). The available symbols are needed, at least, but there are probably other things. – derobert Jan 22 '15 at 17:42
  • 5
    Followup question added at: http://stackoverflow.com/questions/28096133/why-is-l-needed-when-rpath-is-used – Fredrik Johansson Jan 22 '15 at 19:14
  • @n.m. For `gcc`, once `-Wl, -rpath` is used for all the libraries, then `-L` could be omitted. – John Oct 28 '22 at 09:54
  • @John Not in my experience. – n. m. could be an AI Oct 28 '22 at 11:11