介紹GCC在編譯階段和程序運行階段用到的環境變量。
GCC編譯時用到的環境變量
GCC編譯時用到的變量。
C_INCLUDE_PATH
GCC編譯時查找頭文件的目錄列表。比如:
echo $C_INCLUDE_PATH # outputs ## /usr/include:/usr/local/include
CPLUS_INCLUDE_PATH
類似C_INCLUDE_PATH,適用於g++。
LIBRARY_PATH
gcc和g++在編譯的鏈接(link)階段查找庫文件的目錄列表,比如:
echo $LIBRARY_PATH # outputs ## /usr/lib:/usr/lib64:/usr/local/lib:/usr/local/lib64
程序運行時用到的環境變量
程序運行階段用到的變量。
LD_LIBRARY_PATH
程序運行時查找動態鏈接庫(.so文件)的目錄列表。比如:
echo $LD_LIBRARY_PATH # outputs ## /usr/lib:/usr/lib64:/usr/local/lib:/usr/local/lib64
LD_PRELOAD
在LD_PRELOAD(參考man ld.so的LD_PRELOAD部分)中定義的動態鏈接庫會在其他動態鏈接庫之前被加載,因此會覆蓋其他鏈接庫里定義的同名符號(函數變量等),完整的例子可參考test-ld-preload。需要注意的是,在C++中覆蓋C函數庫中的函數時,應使用extern "C"阻止Name Mangling。
su LD_PRELOAD=/usr/lib/libtsocks.so apt-get update
注意,LD_PRELOAD無法在sudo命令里使用。1
Debian動態鏈接庫搜索路徑
Debian系統上,如果修改LD_LIBRARY_PATH沒有用,可修改/etc/ld.so.conf或/etc/ld.so.conf.d/*.conf,將庫目錄作為一行加入以上的conf文件中,然后運行ldconfig命令即可。
vi /etc/ld.so.conf.d/my.conf ldconfig
或者自定義一個庫目錄的配置文件(例如my.conf),然后用ldconfig -f /path/to/my.conf加載該配置文件。
vi ~/project/test/ld_lib.conf ldconfig -f ~/project/test/ld_lib.conf
ld_lib.conf的例子。
/usr/local/lib /path/to/your/shared/lib/directory
ld.so查找庫文件的順序
ld.so用於查找並加載動態鏈接庫文件(*.so),詳情可參考man ld.so。
ld.so loads the shared libraries needed by a program, prepares the program to run, and then runs it. Unless explicitly specified via the -static option to ld dur? ing compilation, all Linux programs are incomplete and require further linking at run time.
The necessary shared libraries needed by the program are searched for in the following order o Using the environment variable LD_LIBRARY_PATH (LD_AOUT_LIBRARY_PATH for a.out programs). Except if the executable is a setuid/setgid binary, in which case it is ignored. o From the cache file /etc/ld.so.cache which contains a compiled list of candidate libraries previously found in the augmented library path. o In the default path /lib, and then /usr/lib.
對於/etc/ld.so.conf.d/里的conf文件,則是按字母序依次加載。假設需要使用/usr/local/lib目錄下的庫文件覆蓋系統的庫文件,可以把包含/usr/local/lib的配置文件排地靠前一些。
$ ls -1 /etc/ld.so.conf.d 00_libc.conf x86_64-linux-gnu.conf zz_i386-biarch-compat.conf $ cat 00_libc.conf /usr/local/lib
閱讀資料
- Environment variables from "An Introduction to GCC"
- LIBRARY_PATH和LD_LIBRARY_PATH環境變量的區別
- Linux: Set OR Change The Library Path
- ld.so(8)
