27

I find that the -L flag must be given when using -rpath. For instance:

gcc -o test test.o -L. -lmylib -Wl,-rpath=.

Why is the -L flag needed? What information more than the information from the h-files are needed at compile time?

If I remove -L. I get the following message:

gcc -o test test.o -lmylib -Wl,-rpath=.
/usr/bin/ld: cannot find -lmyLib

It's perfectly ok to remove both flags, though. Like this:

gcc -o test test.o -lmylib

Provided that libmyLib can be found in /usr/lib, that is. Why isn't -L needed now?

This is a follow-up question to https://stackoverflow.com/a/8482308/1091780.

Jonas G. Drange
  • 8,749
  • 2
  • 27
  • 38
Fredrik Johansson
  • 1,301
  • 1
  • 13
  • 26
  • A linker has no idea what these silly "h files" are. – n. m. could be an AI Aug 30 '17 at 16:07
  • 2
    There are so many possible scenarios where `-L` and `-rpath` should be different. For example, what if you build an executable in your computer and release it to another one's computer? Compile time library search path can not always be the same as runtime library search path. –  Dec 29 '18 at 06:31

2 Answers2

30

Even dynamic libraries required a degree of static linkage; the linker needs to know what symbols should be supplied by the dynamic library. The key difference is that the dynamic library provides the definition at runtime, whilst with fully static library provides the definition at link time.

For this reason, -L is needed to specify where the file to link against is, just as -l specifies the specific library. The . indicates the current directory.

-rpath comes into play at runtime, when the application tries to load the dynamic library. It informs the program of an additional location to search in when trying to load a dynamic library.

The reason -L/usr/lib doesn't need to be specified is because the linker is looking there by default (as this is a very common place to put libraries).

OMGtechy
  • 7,935
  • 8
  • 48
  • 83
  • I still don't understand what type of information that needs to be provided at build time. And look at my last example (I added an example at the end). How come this build time info isn't needed when both flags are removed? – Fredrik Johansson Jan 22 '15 at 21:23
  • 7
    The distinction makes much more sense if you think about scenarios where you aren't building for the build machine (cross compiling or packaging for distribution). You may need to tell the linker to look in one location `-L/home/bob/proj/build/lib` for libs at compile time but a different location `-rpath=/opt/proj/lib` at run time. – dcow Dec 17 '18 at 11:25
5

A clarification of OMGtechy's answer.

If the linker does not check which symbols are provided by a library, it can never tell you if any symbols are missing at compile time. They might be in one of the libraries loaded at run-time. You could never know. There is no connection at compile time between the header files of a library and the .so file.

raahlb
  • 195
  • 2
  • 10