Can "ld" add the rpaths automatically to an executable if it can find the needed dylibs at link time?
The answer to your question is: no, it cannot.
Your question sounds a lot like an XY problem, so first I would recommend going back and reexamine if this really is your main problem, or there's some higher level problem that is actually the problem, you're trying to solve.
First off, I would note that you do not have to use install_name_tool
to set these values after the fact. You can set these while compiling the library and the program. If you're using clang/gcc, you can use the -install_name
option. Similar exists for other compilers.
The reason that ld doesn't automatically add rpaths according to where it found the dylibs is that this would in general produce a binary that runs on your machine, and your machine only. I.e. it is tailored for your specific installation. This is normally not what you want. You want to produce a binary that others can take and run on their computers.
If you're making a "standard project" (i.e. like from an Xcode template) with shared libraries, you won't have to fiddle with rpaths or install names. I.e. usually you have the shared libraries placed at standard locations that are search by the dynamic linker by standard, so that you won't have to define anything special.
However, it seems you're wanting to create something very customized for your usage. If you really want to specify that the dylib is at a specific place (because you only want to run it on your own computer, or computers set up like yours) - you can do so by simply specifying an absolute path for it.
If you want to create something that can easily be copied to other computers without needing seperate installation of dylibs, you often want to bundle your dylib with the application itself. Then you can use a path relative to the executable by using @executable_path
instead of @rpath
.
In my view @rpath is most helpful when you have multiple applications that are "loosely connected" that you would like to share a library that you do not want to place in a system-wide standard location.