[GCC] -rpath 使用相对路径的方式指定动态库位置

2017年12月26日 Linux, Other, 操作系统 暂无评论 阅读 5,107 次

如果我们在编写程序中使用了动态库,在程序运行的时候程序会去系统的相关目录查找动态库,但是我们在移植到嵌入式单板或者把你刚写好的牛逼程序发给你的朋友的时候还要跟他说明用到了那个动态库或者把库发给他,他再部署到自己的系统目录,这样就略显繁琐,我们为什么不就直接把程序和动态库放在一个目录,自己指定动态库相对位置呢,这样把程序和库直接打包发送不就行了吗?这时候gcc中的 -Wl,-rpath就起作用了,它可以把动态库的路径直接写到elf文件中去。


gcc app.c -o app -Lsopath -lmyso -Wl,-rpath=sopath

其中 sopath为动态库搜索路径,libmyso.so为动态库。-L -l都是很熟悉的链接选项了,-Wl,-rpath通过man gcc查看相关的说明。

    Pass option as an option to the linker.  If option contains commas, it is split into multiple options at the commas.  You can use this syntax to pass an argument to the
    option.  For example, -Wl,-Map,output.map passes -Map output.map to the linker.  When using the GNU linker, you can also get the same effect with -Wl,-Map=output.map.

也就是说-Wl为gcc的选项,但是rpath是ld的选项,继续man ld:

    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 isused, 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 file systems.
    For compatibility with other ELF linkers, if the -R option is followed by a directory name, rather than a file name, it is treated as the -rpath option.

rpath指定一个运行动时态库搜索路径,另一种指定runtime library search path的方法是环境变量LD_RUN_PATH,这种方法的缺点是会影响其他程序。