Search

7/31/2006

Static, Shared, Dynamic 函式庫撰寫

Static,Shared, Dynamic 函式庫撰寫
Program Library HOWTO
三個檔案分別為: libhello.c libhello.h demo_use.c
最簡單的作法就是 gcc demo_use.c libhello.c -o result
不過這邊講的是要做成library, 所以以下

[static library]
GCC 的Static Library 副檔名通常為.a。用ar將很多object file 放進一個archive就是static library了。
用法: ar rcs libutil.a util_file.o util_net.o util_math.o
把util_file.o util_net.o util_math.o 產生一個static library叫作libutil.a

step1: 把.c檔都先弄成.o(object)的二進位檔
gcc -c -o libhello.o libhello.c //產生一個libhello.o
gcc -c -o demo_use.o demo_use.c //產生一個demo_use.o

step2:將obj檔弄成static libary的.a檔
ar rcs libhello.a libhello.o //產生一個libhello.a

step3: demo_use.c就可以呼叫static library裏面的函式了, 下面兩種寫法都可
gcc -o result demo_use.o -L. -lhello
gcc -o result demo_use.c libhello.a
* -L.意思是搜尋在目前目錄(.)的library
* Note that we omitted the "lib" prefix and the ".a" suffix when mentioning the library on the link command.

[shared library]

----libhello.c-------
#include
hello(){
printf("hello world\n");
}
---------------------
----main.c-----------
#include
printf("Inside main\n");
hello();
return 0;
}
---------------------

step1: gcc -fPIC -c libhello.c
The -fPIC option is to tell the compiler to create Position Independent Code (create libraries using relative addresses rather than absolute addresses because these libraries can be loaded multiple times).

step2: gcc -shared -o libmylib.so libhello.o
將數個.o檔做成一個.so檔
The -shared option is to specify that an architecture-dependent shared library is being created.

step3: gcc -c -o main.o main.c

step4:
gcc -o result -L. -lhello main.o

執行:
LD_LIBRARY_PATH="." ./result

[dynamic loading]
#include <dlfcn.h> /* defines dlopen(), etc.       */
#include
<stdio.h>
 
main(){
void *libc; /* handle of the opened library */
void (*printf_call)();
/* define a function pointer variable to hold the function's address */

if(libc=dlopen("/lib/libc.so.5",RTLD_LAZY)){
/*use the lazy approach(RTLD_LAZY) of checking only when used */
printf_call=dlsym(libc,"printf");
/*Calling Functions Dynamically Using dlsym()*/
(*printf_call)("hello, world\n");
}
}
"When we discussed static libraries we said that the linker will try to look for a file named 'libutil.a'. We lied. Before looking for such a file, it will look for a file named 'libutil.so' - as a shared library. Only if it cannot find a shared library, will it look for 'libutil.a' as a static library. Thus, if we have created two copies of the library, one static and one shared, the shared will be preferred. This can be overridden using some linker flags ('-Wl,static' with some linkers, '-Bstatic' with other types of linkers."

參考資料
Creating Libraries
GCC產生Static Library
Building And Using Static And Shared "C" Libraries
用Open Source工具開發軟體

沒有留言: