Linux上生成動態庫的方法比在Windows平臺上簡單很多。得益於強大的gcc,只需一步就可以生成共享庫。
編寫源碼
寫一個簡單的例子, MyLibrary.h和MyLibrary.c
#ifndef _MYLIBRARY_H__
#define _MYLIBRARY_H__
void MyPrint()
#endif
#include <stdio.h>
#include "MyLibrary.h"
void MyPrint()
{
printf("this is message from MyLibrary\n");
}
編譯共享庫
gcc -fPIC -shared MyLibrary.c -o libMyLibrary.so.1
fPIC是編譯選項,表示位置無關代碼(Position Independent Code), -shared是鏈接選項,表示生成共享庫而不是可執行文件。
上述命令還可以分爲兩個步驟
gcc -c -fPIC MyLibrary.c -o MyLibrary.o
gcc -shared MyLibrary.o -o libMyLibrary.so.1