GNU ld の -R/-rpath オプション2007年06月01日 11時37分33秒

GNU ld でいくつか気になった事。

% man ld
       -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.  The -rpath option
           is also used when locating  shared  objects  which  are  needed  by
           shared objects explicitly included in the link; see the description
           of the -rpath-link option.  If -rpath is not used when  linking  an
           ELF   executable,   the   contents   of  the  environment  variable
           "LD_RUN_PATH" will be used if it is defined.

           The -rpath option may also be used on SunOS.  By default, on SunOS,
           the  linker  will  form  a  runtime  search patch out of all the -L
           options it is given.  If a  -rpath  option  is  used,  the  runtime
           search  path  will  be formed exclusively using the -rpath options,
           ignoring the -L options.  This can be useful when using gcc,  which
           adds many -L options which may be on NFS mounted filesystems.

           For  compatibility with other ELF linkers, if the -R option is fol-
           lowed by a directory name, rather than a file name, it  is  treated
           as the -rpath option.

とある。-rpath は実行形式に動的リンクのサーチパスを埋め込む。-R でディレクトリを指定しても同じ動作をする。いくつか、ここには書かれていない動作や詳細があるので、少々手間取った。

-rpath は ld のオプションで、-rpath の後にスペースが必要だ。無いと、間違ったオプションと解釈される。

-rpath と -R は ld のオプションとなるため、gcc を通して指定するときは、-Wl か -Wlinker などを使い、ld に渡してやる必要がある。

また、-rpath と -R はバイナリにサーチパスを埋め込むコマンドだ。別の言い方をすると ldd で使われる物。サーチパスを足したのだから ld でも使われるのかと思い込んでいたが、どうもそうではないらしい。-L を用いて、-R で指定したパスを指定し直す必要があった。-L を指定しないと、-R にしかないライブラリのリンクに失敗する。