链接选项-rpath
-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 environ- ment variable "LD_RUN_PATH" will be used if it is defined.
rpath链接选项主要有两个功能:
(1)程序运行时,优先到rpath指定的目录去寻找依赖库
(2)程序链接时,在指定的目录中,隐式的链接那些动态库所需要的链接库。
例如:
有我们需要链接liba.so,但是liba.so依赖库libb.so 和 libc.so,我们再编写makefile时不需要显示的链接所有的库,只要将liba.so,libb.so 和 libc.so拷贝的同一个目录中,然后利用rpath链接应用程序,这样编译便不需要显示的去链接liba.so所依赖的库了。
如:gcc -o test test.c -I. -L. -la -Wl,-rpath=./
但是需注意是链接器选项所以需要前面使用-Wl选项告诉编译器将后面的参数传递给链接器。