同一份 C++ 程式碼要在 HP-UX、Solaris 與 Windows 上都以動態庫(Shared Library / DLL)形式運作,差異比想像中小,但每個平台的著力點不同。在 Unix 這邊,主要工作在於寫對 makefile 與編譯器旗標;而在 Windows 上,還多了一道手續——必須為要對外導出的類別與函式加上修飾。本文把三個平台的完整做法整理出來,並附上一個可直接編譯的範例。
整個範例由一個動態庫與一個呼叫它的執行檔構成:
使用 HP 自帶的 aCC 編譯器:
rm *.o rm *.sl aCC +z mytime.cpp # +z 產生可用於動態庫的 *.o(位置無關碼) aCC -b -o libmy.sl mytime.o # -b 產生動態庫,成品名為 libmy.sl aCC dy.cpp libmy.sl # 連結成執行檔,預設 a.out,也可用 -o 指定名稱
關鍵是 +z 與 -b 這兩個旗標:前者讓目的檔成為位置無關碼,後者才會產生共享庫而非一般執行檔。
使用 Workshop 附的 CC:
CC -c mytime.cpp # -c 只編譯成 *.o CC -G -o libmy.so mytime.o # -G 產生動態庫 libmy.so CC -Bdynamic -o myee libmy.so dy.cpp # 連結出執行檔 myee
Solaris 在執行前需要以 root 身分把庫放到系統搜尋路徑,或用語系系結指向實際位置:
ln -s /export/home/hurh/tdll/libmy.so /lib
對照記憶:HP 用 +z / -b,Solaris 用 -G / -Bdynamic,本質相同,只是旗標命名不同。
Windows 的動態庫必須明確宣告哪些符號要對外公開,做法是在宣告上用 __declspec(dllexport) 標記;而使用方(引用程式)則用 __declspec(dllimport)。實務上很少手寫兩份,而是用巨集搭配兩個編譯期旗標自動切換。
以下為 mytime.h 的宣告寫法:
#ifndef MYTIME_H
#define MYTIME_H
#ifdef WIN32
# ifdef JESTERDLL
# define DLLT_API __declspec(dllexport)
# else
# define DLLT_API __declspec(dllimport)
# pragma comment(lib, "dllt1.lib")
# endif
#else
# define DLLT_API
#endif
struct DATETYPE { int year; int mon; int day; };
struct TIMETYPE { char hour; char min; char sec; };
int DLLT_API getdate(DATETYPE *d);
int DLLT_API gettime(TIMETYPE *t);
class DLLT_API gqlass {
public:
int ineid;
void setneid(int neid);
gqlass();
~gqlass();
};
#endif
這裡的設計重點在於兩個巨集搭配使用:
/D 選項),此時 DLLT_API 展開為 __declspec(dllexport)。DLLT_API 自動變成 __declspec(dllimport)。另外,寫上 #pragma comment(lib, "dllt1.lib") 之後,就不必再在專案設定或 makefile 裡指定要連結的引入庫,這在跨平台專案裡能省下不少條件判斷。
#include "stdafx.h"
#include "time.h"
#include "mytime.h"
int getdate(DATETYPE *d)
{
long ti;
struct tm *tm;
time(&ti);
tm = localtime(&ti);
d->year = tm->tm_year + 1900;
d->mon = tm->tm_mon + 1;
d->day = tm->tm_mday;
return 0;
}
int gettime(TIMETYPE *t)
{
long ti;
struct tm *tm;
time(&ti);
tm = localtime(&ti);
t->hour = tm->tm_hour;
t->min = tm->tm_min;
t->sec = tm->tm_sec;
return 0;
}
gqlass::gqlass() { ineid = 0; }
gqlass::~gqlass() { }
void gqlass::setneid(int neid)
{
ineid = neid;
}
#include "stdafx.h"
#include "stdio.h"
#include "../dllt1/mytime.h"
int main()
{
DATETYPE d;
TIMETYPE t;
puts("動態連結庫應用示範");
getdate(&d); /* 呼叫共享函式 */
printf("當前日期: %04d-%02d-%02d\n", d.year, d.mon, d.day);
gettime(&t); /* 呼叫共享函式 */
printf("當前時間: %02d:%02d:%02d\n", t.hour, t.min, t.sec);
gqlass gq;
printf("before setneid gq.ineid=%d\n", gq.ineid);
gq.setneid(123);
printf("after setneid gq.ineid=%d\n", gq.ineid);
return 0;
}
類別也要修飾。許多人只替自由函式加上 export/import,卻漏掉 class,結果連結成功但呼叫端拿不到符號。範例中 class DLLT_API gqlass 就是為了避免這個問題。
條件判斷要寫對。切換 export 與 import 的判斷必須是「有定義 WIN32 才進入 Windows 分支」,否則在非 Windows 平台反而會展開成 MSVC 專屬的 __declspec,直接編譯失敗。
Unix 端別忘了執行期路徑。動態庫編出來只是第一步,執行檔啟動時仍要能找到 .so / .sl。除 root 建語系系結之外,正式專案更常用 -R(Solaris)或 LD_LIBRARY_PATH 這類做法來處理。