gcc rpath

linux環境在執行程式時,為了將.so library統一放在特定地方而不想更動LD_LIBRARY_PATH或是/etc/ld.so.conf時,
可透過在gcc編譯選項加上

-Wl,-rpath=.
-Wl,-rpath=./lib

這樣會搜尋執行檔當前目錄的相對路徑(. 即是當前目錄, ./lib 即是當前目錄/lib)
但注意當前目錄不等同執行檔所在位置的目錄(也就是從其他目錄執行程式),
所以如果.so是放在執行檔所在目錄下的lib,而從其他目錄執行時,一樣會報錯。
一般情況預期的相對目錄是相對於執行檔的目錄,這時候就需要加入$ORIGIN 標示。

-Wl,-rpath,’$$ORIGIN/.’

注意Makefile裡以上是兩個dollar sign
確認是否正確可用readelf debug: readelf -d executable|grep PATH

少一個$ '$ORIGIN/.'
0x000000000000000f (RPATH) Library rpath: [RIGIN/.]

這邊rpath描述的是執行時的,另外有一個rpath-link是編譯時期的
參考:
https://linux.die.net/man/1/ld
https://stackoverflow.com/questions/24573732/difference-between-relative-path-and-using-origin-as-rpath
https://stackoverflow.com/questions/38058041/correct-usage-of-rpath-relative-vs-absolute

chrpath

This entry was posted in Tips. Bookmark the permalink.

Leave a Reply