發表文章

目前顯示的是 12月, 2013的文章

shared library 筆記

source:  http://www.thegeekstuff.com/2012/06/linux-shared-libraries/ 無聊來練一下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 #include extern unsigned int add(unsigned int a, unsigned int b); 3.編釋囉 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/l

Linux library筆記

這文章是static library的筆記,首先我們先寫兩個簡單的function當library要用的。 #include <stdio.h> void bill(char arg) { printf("Bill say:%s \n",arg); } #include <stdio.h> void lucy(int arg) { printf("lucy say+1:%d\n",(arg+1)); } 因為沒有main function是不能編成執行檔的。  $ gcc lucy.c /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../crt1.o: In function `_start': (.text+0x18): undefined reference to `main' collect2: ld returned 1 exit status  所以要加這個參數 -c Compile and assemble, but do not link  $ gcc -c bill.c lucy.c  $ ls  bill.c bill.o lucy.c lucy.o #include <stdio.h> #include <stdlib.h> #include "mylib.h" int main() { lucy(11); exit(0); } 編釋寫好的測式程式。  $ gcc -o go carlos.c bill.o lucy.o  $ ./go lucy say+1:12 這樣一來calros.c 就可以連接到lucy.o的function. 接下來我們來試著產生static的library *.a檔。 我把lib名稱取叫ks  $ ar crv libks.a bill.o lucy.o a - bill.o a - lucy.o  $ ls bill.c bill.o carlos.c go libks.a lucy.c lucy.o mylib.h   $ gcc -o go carlos.c