int main() { test(); }
man.c如上:
#include <stdio.h> void test() { printf("test\n"); }
test.c 如上:
將test.c與main.c轉換為目標文件test.o,main.o:
gcc -c main.c test.c
將兩者鏈接成可執行文件:
gcc test.o main.o -o liu
將test.o打包為動態庫文件libtest.so:
gcc -fPIC -c test.c -o test.o
gcc --share test.o -o libtest.so
or:
gcc -fPIC -shared test.c -o libtest.so
將test.o打包為靜態庫文件libtest.a:
ar r libtest.a test.o
不能寫成:
ar r libtest.a test.c
否則會出現錯誤。
編譯鏈接動態庫(gcc是默認鏈接動態庫):
gcc main.c -L. -ltest -o main
-L.表示動態鏈接庫在當前路徑下,若是在其他路徑下應該執行以下命令:
gcc main.c -L /xx/yy -ltest -o main
編譯鏈接靜態庫:
gcc main.c -L. libtest.a -o main
或者:
gcc main.c -L. -static -ltest -o main
可執行文件:
./main
注意需要將動態庫文件放到系統目錄中。