Static link:

Compiler時,

library加入程式碼

優:快

劣:佔空間

 

Dynamic Link:

Compiler時,不將library加入程式碼,執行程式的時後,再將 library載入程式碼,若有多個程式共用同一個library,只需載一個librarymemory

優:省空間

劣:慢

 

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

 

Using a Static Library:

# gcc –o main main.c –L. –lmylib

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

  2. Create a shared library named libmylib.so
    # gcc -shared libmylib.so file1.c file2.c file3.c

 

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 libmylib.so file1.c file2.c file3.c

 

 

Using a Shared Library:

  1. (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);

  1. 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

 

example

dltest.c

#include <dlfcn.h>

 

int main()

{

void *handle;

void (*f)();

char *error;

 

/* open the needed object */

handle = dlopen(『./libmylib.so』, RTLD_LAZY);

if(!handle) {

/* get diagnostic information */

fputs(dlerror(), stderr);

exit(1);

}

 

/* find the address of function and data objects */

f = dlsym(handle, 『function1″);

if ((error = dlerror())!=NULL) {

fprintf(stderr, 『%s\n』, error);

exit(1);

}

 

/* excute function1 */

f();

 

/* close a dlopen object */

dlclose(handle);

}

用 ar 指令組合成 static library.
(注意: 你的程式庫一定要加 lib名稱)

-r: 新增 fun.o 到 libfun.a 中

-c: 建立新的程式庫

-s: 將一個 object 檔的 index 寫入程式庫

指令:  ar rcs lib程式庫名稱 a.o b.o c.o

http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html

arrow
arrow
    全站熱搜

    phchiu 發表在 痞客邦 留言(0) 人氣()