LIBRARY_PATH和LD_LIBRARY_PATH的区别

关于Linux gcc中的 LIBRARY_PATH 和 LD_LIBRARY_PATH 参数说明

下面摘取了两篇较权威的说明资料:

  • GNU 上关于LIBRARY_PATH的说明
LIBRARY_PATH
The value of LIBRARY_PATH is a colon-separated list of directories, much like PATH.
When configured as a native compiler, GCC tries the directories thus specified when searching for special linker files, if it can't find them using GCC_EXEC_PREFIX.
Linking using GCC also uses these directories when searching for ordinary libraries for the -l option (but directories specified with -L come first).
  • man7 上关于LD_LIBRARY_PATH的说明
LD_LIBRARY_PATH
A colon-separated list of directories in which to search for ELF libraries at execution-time. Similar to the PATH environment variable. Ignored in set-user-ID and set-group-ID programs.
  • StackOverflow 上关于 LIBRARY_PATH 和 LD_LIBRARY_PATH 的解释更直白
LIBRARY_PATH is used by gcc before compilation to search for directories containing libraries that need to be linked to your program.

LD_LIBRARY_PATH is used by your program to search for directories containing the libraries after it has been successfully compiled and linked.

EDIT: As pointed below, your libraries can be static or shared.
If it is static then the code is copied over into your program and you don't need to search for the library after your program is compiled and linked.
If your library is shared then it needs to be dynamically linked to your program and that's when LD_LIBRARY_PATH comes into play.
总结

关于 LIBRARY_PATH 和 LD_LIBRARY_PATH 的关系,总结如下。

  • Linux gcc编译链接时的动态库搜索路径
GCC编译、链接生成可执行文件时,动态库的搜索路径顺序如下
1、gcc编译、链接命令中的-L选项;
2、gcc的环境变量的LIBRARY_PATH(多个路径用冒号分割);
3、gcc默认动态库目录:/lib:/usr/lib:usr/lib64:/usr/local/lib。
4.2 执行二进制文件时的动态库搜索路径

注意不会递归性地在其子目录下搜索!

  • 链接生成二进制可执行文件后,在运行程序加载动态库文件时,搜索的路径顺序如下
- 编译目标代码时指定的动态库搜索路径:用选项-Wl,rpath和include指定的动态库的搜索路径,比如gcc -Wl,-rpath,include -L. -ldltest hello.c,在执行文件时会搜索路径`./include`;
- 环境变量LD_LIBRARY_PATH(多个路径用冒号分割);
- 在 /etc/ld.so.conf.d/ 目录下的配置文件指定的动态库绝对路径(通过ldconfig生效,一般是非root用户时使用);
- gcc默认动态库目录:/lib:/usr/lib:usr/lib64:/usr/local/lib等。
  • Linux GCC默认的动态库搜索路径可以通过 ld –verbose 命令查看:
[genewiznj@njgate01 picrust]$ ld --verbose |grep -i search_dir
SEARCH_DIR("/usr/x86_64-redhat-linux/lib64"); SEARCH_DIR("/usr/lib64"); SEARCH_DIR("/usr/local/lib64"); SEARCH_DIR("/lib64"); SEARCH_DIR("/usr/x86_64-redhat-linux/lib"); SEARCH_DIR("/usr/local/lib"); SEARCH_DIR("/lib"); SEARCH_DIR("/usr/lib");
0%