Linux gcc中的LIBRARY_PATH 和 LD_LIBRARY_PATH
1、 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).
2、 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.
3、 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.
总结
1.Linux gcc编译链接时的动态库搜索路径
GCC编译、链接生成可执行文件时,动态库的搜索路径顺序如下(注意不会递归性地在其子目录下搜索):
1、gcc编译、链接命令中的-L选项; 2、gcc的环境变量的LIBRARY_PATH(多个路径用冒号分割); 3、gcc默认动态库目录:/lib:/usr/lib:usr/lib64:/usr/local/lib。
2.执行二进制文件时的动态库搜索路径
链接生成二进制可执行文件后,在运行程序加载动态库文件时,搜索的路径顺序如下:
1、编译目标代码时指定的动态库搜索路径:用选项-Wl,rpath和include指定的动态库的搜索路径,比如gcc -Wl,-rpath,include -L. -ldltest hello.c,在执行文件时会搜索路径`./include`; 2、环境变量LD_LIBRARY_PATH(多个路径用冒号分割); 3、在 /etc/ld.so.conf.d/ 目录下的配置文件指定的动态库绝对路径(通过ldconfig生效,一般是非root用户时使用); 4、gcc默认动态库目录:/lib:/usr/lib:usr/lib64:/usr/local/lib等。
其中,Linux GCC默认的动态库搜索路径可以通过 ld --verbose
命令查看:
[root@typecodes tcpmsg]# ld --verbose ............ SEARCH_DIR("/usr/x86_64-redhat-linux/lib64"); SEARCH_DIR("/usr/local/lib64"); SEARCH_DIR("/lib64"); SEARCH_DIR("/usr/lib64"); ##### 64位系统 SEARCH_DIR("/usr/x86_64-redhat-linux/lib"); SEARCH_DIR("/usr/local/lib"); SEARCH_DIR("/lib"); SEARCH_DIR("/usr/lib");
此外,可以设置多个搜索目录,这些目录之间用冒号分隔开。
参考:
http://typecodes.com/cseries/gcclderrlibrarypath.html
https://blog.csdn.net/yansmile1/article/details/72236057