2012年1月12日 星期四

static link & Dynamic Link & Dynamic Load

【轉貼】 一天一成長
Static link:
Compiler時,library加入程式碼
優:快
劣:佔空間
Dynamic Link:
Compiler時,不將library加入程式碼,執行程式的時後,再將 library載入程式碼,若有多個程式共用同一個library,只需載一個library進memory
優:省空間
劣:慢
Dynamic Load:
Compiler時,不將library加入程式碼,執行程式時,遇到函式,才將library載入,用完後再free出空間
優:更省空間
劣:更慢
==========================
Static Link
Creating a Static Library:
  1. Compile source codes
    # gcc –c file1.c file2.c file3.c
  2. Create a static library named libmylib.a
    # ar rcs libmylib.a file1.o file2.o file3.o
    -r: 新增 *.o 到 libfun.a 中
    -c: 建立新的程式庫
    -s: 將一個 object 檔的 index 寫入程式庫
  3. Using a Static Library:
    # gcc –o main main.c –L. –lmylib (lib不用打)
    Parameters:
    -L: the directory of the library
    -l: the name of the library
Dynamic Link
Creating a Shared Library:
  1. Compile source codes
    # gcc -c file1.c file2.c file3.c
    or
  2. 加上-fPIC用來產生position-independent code # gcc -c -fPIC file1.c file2.c file3.c
  3. Create a shared library named libmylib.so
    # gcc -shared -o libmylib.so file1.o file2.o file3.o
  4. Using a Shared Library:
    # gcc –o main main.c –L. –lmylib
    Note: Remember to put libmylib.so into PATH, ex. /usr/lib
Dynamic Load (還沒用過)
Creating a Shared Library:
  1. Compile source codes;
    # gcc –c file1.c file2.c file3.c
  2. Create a shared library named libmylib.so
    # gcc -shared -o file1.o file2.o file3.o libmylib.so
  3. Using a Shared Library:
    (Reference: http://linux.die.net/man/3/dlopen)
    Use the following function to access the shared library:
    #include <dlfcn.h>
    void *dlopen(const char *filename, int flag);
    char *dlerror(void);
    void *dlsym(void *handle, const char *symbol);
    int dlclose(void *handle);
    Compile: Since above function are implemented in the library libdl.a, we need to load this library
    # gcc dltest.c –ldl
    Parameters:
    -ldl: load the library libdl.a
ref:

沒有留言:

張貼留言