咱們知道,PostgreSQL能夠支持幾乎(這個詞彷佛能夠不要)全部主流平臺,平臺間尤爲Windows與*nix之間的API差別巨大,PG是怎麼作到的呢,用一個簡單的例子解釋。mysql
前邊我寫怎麼在Windows下編譯mysql_fdw提到過的修改:linux
#include "dynloader.h"
mysql_dll_handle = dlopen(_MYSQL_LIBNAME, RTLD_LAZY | RTLD_DEEPBIND); 改成 mysql_dll_handle = dlopen(_MYSQL_LIBNAME, 1);
更正規的寫法是sql
#if defined(__APPLE__) || defined(__FreeBSD__) mysql_dll_handle = dlopen(_MYSQL_LIBNAME, RTLD_LAZY); #elif defined WIN32 mysql_dll_handle = pg_dlopen(_MYSQL_LIBNAME, 1); #else mysql_dll_handle = dlopen(_MYSQL_LIBNAME, RTLD_LAZY | RTLD_DEEPBIND); #endif
這裏並無修改原有兩行,只是爲展現應該怎麼寫,模塊代碼的跨平臺性纔會更好些。數據庫
dynloader.h在編譯前會根據平臺指向正確的頭文件,在Windows下指向 src/backend/port/dynloader/win32.hbash
#define pg_dlopen(f) dlopen((f), 1) #define pg_dlsym dlsym #define pg_dlclose dlclose #define pg_dlerror dlerror char *dlerror(void); int dlclose(void *handle); void *dlsym(void *handle, const char *symbol); void *dlopen(const char *path, int mode);
Windows下封裝了庫載入的系列函數,它們實如今 src/backend/port/dynloader/win32.c,節選:ide
void * dlopen(const char *path, int mode) { HMODULE h; int prevmode; /* Disable popup error messages when loading DLLs */ prevmode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX); h = LoadLibrary(path); SetErrorMode(prevmode); if (!h) { set_dl_error(); return NULL; } last_dyn_error[0] = 0; return (void *) h; }
最終,仍然是調用傳統的Windows函數LoadLibrary。函數
前文還提到修改Solution.pm,只爲mysql_fdw添加庫和頭文件路徑,避免影響其餘模塊。由於mysql有些頭文件跟PG定義衝突,你們都是關係數據庫,不免有些東西的命名會相同 @_@。.net
上邊說的是編譯系統自動識別當前平臺,編譯不一樣源文件,*nix平臺是在configure腳本里。3d
平臺判斷:code
case $host_os in aix*) template=aix ;; cygwin*) template=cygwin ;; darwin*) template=darwin ;; dragonfly*) template=netbsd ;; freebsd*) template=freebsd ;; hpux*) template=hpux ;; linux*|gnu*|k*bsd*-gnu) template=linux ;; mingw*) template=win32 ;; netbsd*) template=netbsd ;; openbsd*) template=openbsd ;; solaris*) template=solaris ;; esac
指定軟鏈文件(好比macOS會指向 src/backend/port/dynloader/darwin.h)
"src/include/dynloader.h") CONFIG_LINKS="$CONFIG_LINKS src/include/dynloader.h:src/backend/port/dynloader/${template}.h" ;;
再來看Windows(Solution.pm中),用的是拷貝方式:
if (IsNewer( 'src/include/dynloader.h', 'src/backend/port/dynloader/win32.h')) { copyFile('src/backend/port/dynloader/win32.h', 'src/include/dynloader.h'); }
固然,代碼裏更多的是傳統preprocessor方式:
#ifdef WIN32 /* Win32 does not have UTF-8, so we need to map to UTF-16 */ if (GetDatabaseEncoding() == PG_UTF8 && (!mylocale || mylocale->provider == COLLPROVIDER_LIBC)) { ... #endif /* WIN32 */
我開通了本身的公衆號,文章會同步發,歡迎關注。