(1)Linux下編寫動態連結程式庫。通常靜態連結庫是編譯的時候和源檔案一起編譯產生可執行檔的。動態連結程式庫則不是,它是一個已經編譯好的檔案(靜態則不是),只有當程式啟動並執行時候(但是編譯的時候要將動態連結程式庫的資訊載入進來),它才去找動態連結程式庫拿它想用的一些函數。而且動態連結程式庫可以提高通用性,編寫一個動態連結程式庫可以讓很多人一起用。有點類似類?
test_so.h
#ifndef _TEST_SO_H#define _TEST_SO_H #include <stdio.h>#include <stdlib.h> void test_a();void test_b();void test_c(); #endif
test_a.c
#include "test_so.h" void test_a(){ printf("this is test_a()\n");}
test_b.c
#include "test_so.h"void test_b(){ printf("this is test_b()\n");}
test_c.c
#include "test_so.h"void test_c(){ printf("this is test_c()\n");}
然後將這些檔案編譯為動態連結程式庫gcc test_a.c test_b.c test_c.c --shared -fPIC -o libtest.so,則產生libtest.so檔案(它已經編譯好了),和普通可執行程式不同,它並沒有main()。
在看如何調用它
編寫test.c
#include "test_so.h" int main(void){ test_a(); test_b(); test_c(); return 0;}
gcc test.c -L . -ltest -o test ((-L .)表示動態連結程式庫在本目錄, (-ltest)表示動態連結程式庫的名字為lib(test).so)。
然後通過ldd ./test查看有哪些動態連結程式庫和可執行程式有關聯。
結果發現libtest.so沒有關聯。
運行./test出現:
./test: error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory
也就是說找不到這個動態連結程式庫,但是我們已經在編譯test.c的時候加入路徑了?
這時候修改LD_LIBRARY_PATH變數
#vim ~/.bashrc添加:LD_LIBRARY_PATH = $LD_LIBRARY_PATH:/home/xxx/Testexport LD_LIBRARY_PATH退出以後#source ~/.bashrc
或者/etc/ld.so.conf添加動態連結程式庫的路徑。
#vim /etc/ld.so.conf添加一行:/home/xxx/Test然後重新整理一把#/sbin/ldconfig -v再編譯執行成功。