shared library 筆記
source: http://www.thegeekstuff.com/2012/06/linux-shared-libraries/
無聊來練一下shared library好了。
1.先寫好share.c
gcc -c -Wall -Werror -fPIC share.c
gcc -shared -o libshare.so share.o
4.產生出來libshare.so囉!!!
# ls
libshare.so share.c share.h share.o
5.寫一個測式的程式
include
#include"share.h"
int main(void)
{
unsigned int a = 1;
unsigned int b = 2;
unsigned int result = 0;
result = add(a,b);
printf("\n The result is [%u]\n",result);
return 0;
}
# gcc -L. -Wall sharetest.c -o go -lshare
-L. 在當前的目錄下,找-lshare 名稱為libshare.so的library來編。
# go
./go: error while loading shared libraries: libshare.so: cannot open shared object file: No such file or directory
go的測試程式找不到需要的libshare.so。
這時有兩個方法可以解決
a.修改/etc/ld.so.conf 然後執行ldconfig
vim /etc/ld.so.conf
include ld.so.conf.d/*.conf
/usr/local/openssl/lib/
/usr/lib
/home/carlosnew/Cpratic
b.export LD_LIBRARY_PATH=/home/carlosnew/Cpratic:$LD_LIBRARY_PATH
6最後一看一下執行結果!
# go
Inside add()
The result is [3]
static library會佔用較多的記憶體因為把要用到的functions都先包進去了,但是執行速度會比較快,shared library執行速會比較慢,相同的function只需要一塊記憶體空間。
無聊來練一下shared library好了。
1.先寫好share.c
#include "shared.h" unsigned int add(unsigned int a, unsigned int b) { printf("\n Inside add()\n"); return (a+b); }2.share.h
#include3.編釋囉extern unsigned int add(unsigned int a, unsigned int b);
gcc -c -Wall -Werror -fPIC share.c
gcc -shared -o libshare.so share.o
4.產生出來libshare.so囉!!!
# ls
libshare.so share.c share.h share.o
5.寫一個測式的程式
include
#include"share.h"
int main(void)
{
unsigned int a = 1;
unsigned int b = 2;
unsigned int result = 0;
result = add(a,b);
printf("\n The result is [%u]\n",result);
return 0;
}
# gcc -L. -Wall sharetest.c -o go -lshare
-L. 在當前的目錄下,找-lshare 名稱為libshare.so的library來編。
# go
./go: error while loading shared libraries: libshare.so: cannot open shared object file: No such file or directory
go的測試程式找不到需要的libshare.so。
這時有兩個方法可以解決
a.修改/etc/ld.so.conf 然後執行ldconfig
vim /etc/ld.so.conf
include ld.so.conf.d/*.conf
/usr/local/openssl/lib/
/usr/lib
/home/carlosnew/Cpratic
b.export LD_LIBRARY_PATH=/home/carlosnew/Cpratic:$LD_LIBRARY_PATH
6最後一看一下執行結果!
# go
Inside add()
The result is [3]
static library會佔用較多的記憶體因為把要用到的functions都先包進去了,但是執行速度會比較快,shared library執行速會比較慢,相同的function只需要一塊記憶體空間。
留言