user22180
user22180

Reputation: 561

Why doesn't -L automatically include -rpath when shared library is used?

I don't get why it is necessary to provide either rpath or set env varible using LD_LIBRARY_PATH when -L already tells where the shared Library path is.

this answer says: -L tells ld where to look for libraries to link against when linking.

But why at the same time the corresponding -rpath is not set automatically? why do we need to do it manually again?

P.S: I guess if you had that feature, then the executable would be useless in some other environment. But if it is so then what ld actually does during linking, or why it is necessary to give -L path if -rpath in some other environment is different.

Upvotes: 3

Views: 2252

Answers (2)

Yizhe
Yizhe

Reputation: 235

In theory, GNU ld could totally implement a feature flag which, if enabled, adds RPATH automatically when a shared library is used.

CMake provides just that: INSTALL_RPATH_USE_LINK_PATH

Add paths to linker search and installed rpath.

INSTALL_RPATH_USE_LINK_PATH is a boolean that if set to TRUE will append to the runtime search path (rpath) of installed binaries any directories outside the project that are in the linker search path or contain linked library files. The directories are appended after the value of the INSTALL_RPATH target property.

Upvotes: 0

Geoff Nixon
Geoff Nixon

Reputation: 4994

It's definitely not a "misfeature of the linker".

-L (a much older flag) simply tells the linker to look in that directory for any library that matches any subsequent -l flag, including static libraries/archives (remember, in times of yore, this was the only kind of library). It intentionally remains a link-time only flag; it has no effect after the linker's business is complete.

-rpath is an entirely different beast. Its purpose is to embed in an executable or shared/dynamic library a list of one or more paths to search for dynamic libraries, when the necessary symbols are looked up in shared libraries at runtime (the r in -rpath).

There are many instances where one would want -L but not -rpath; particularly when one specifically wants to link a static library rather than defer to the dynamic linker. It is relatively trivial on most platforms to override a built-in rpath, i.e., with the LD_PRELOAD environmental variable, and some actually consider this a security issue.

Perhaps ake a look at http://sta.li/faq for a compelling case against dynamic linkage.

Upvotes: 5

Related Questions