static link & Dynamic Link & Load

原文:http://leterboy.wordpress.com/2009/10/26/static-link-dynamic-link-load/

 

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 rcslib程式庫名稱 a.o b.o c.o

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值