[C] 關於 shared library

今晚來複習一下shared library的建置好了, 主要有三個步驟:
1)建立 object codes (.h跟.c檔)
2)建立 library
>root#gcc -Wall -fPIC -c test.c
-Wall:顯示warning message
-fPIC:compile產生position independent code. *PIC大小寫有差異.
>> 產生 test.o

>root#gcc -shared -Wl,-soname,libtest.so.1 -o libtest.so.1.0 *.o
-shared:產生為shared object
-Wl:將參數傳給linker, 這裡的參數是 "-soname libtest.so.1". 需要注意的是逗號之間不可以留空白!!!
>> 產生 libtest.so.1.0

3)建立 link (optional)
通常會建立 libtest.so 跟 libtest.so.1
>> ln -sf /path/to/libtest.so.1.0 libtest.so
>> ln -sf /path/to/libtest.so.1.0 libtest.so.1
libtest.so 是提供其他檔 ex. abc.c檔要compile時, 做naming conversion用 (即 -ltest)
libtest.so.1 則是提供執行 abc 時, 做 runtime binding用。


如此在編譯其他的abc.c檔時
>> gcc -Wall -L/path/to/libtest.so -ltest test.c -o test

然後在執行abc時, 記得將 path/to/libtest.so 加入 $LD_LIBRARY_PATH 中。
當然也可以修改ld.so.conf或執行時指定.so路徑。
另外可以下 ldd test 檢查 executable 所link 的library是否正確。

Comments

Popular posts from this blog

股票評價(Stock Valuation) - 股利折現模型

openwrt feed的使用

How to convert Markdown into HTML