https://blog.csdn.net/tttyd/article/details/8722276
方法一:在配置文件/etc/ld.so.conf中指定動態庫搜索路徑。
vi /etc/ld.so.conf
添加 lib目錄
ldconfig
方法二:通過環境變量LD_LIBRARY_PATH指定動態庫搜索路徑。
export LD_LIBRARY_PATH=”LD_LIBRARY_PATH:/opt/”
方法三:在編譯目標代碼時指定該程序的動態庫搜索路徑。
還可以在編譯目標代碼時指定程序的動態庫搜索路徑。通過gcc 的參數”-Wl,-rpath,”指定
其中方法三可以避免安裝部署的麻煩
方法三示例
假設main.cpp,hello.h,hello.cpp,其中main.cpp調用了hello類中的方法
1 生成hello.so
g++ -shared hello.cpp -o libhello.so
2 編譯main.cpp,並鏈接,並指定運行時libhello.so的位置
g++ main.cpp -lhello -L./ -Wl,-rpath=./ -o main
值得一提的是,如果采用帶版本號的庫,例如libhello.so.2
鏈接命令可使用g++ main.cpp libhello.so.2 -L./ -Wl,-rpath=./ -o main
2)加入第二個so庫
g++ main.cpp -L./second/ -Wl,-rpath=./second/ -lsecond -L./hello/ -Wl,-rpath=./hello/ -lhello -o main
ps,遇到過一個奇怪的問題,就是假設libhello.so還用到了libother.so,由於在/etc/ld.so.conf里配置錯誤了libother.so的目錄路徑,導致一直產生undefined reference to錯誤,但是在工程里對libother目錄路徑配置是正確的,有可能於查找路徑順序有關