6. 移植性設計規範本規範中只討論C++應用程式在不同的作業系統(如Linux和Windos作業系統)平台之間的移植性。l
推薦不要加入移植性設計,如果需求/軟體架構沒有明確要支援可移植性。l
推薦盡量使用C標準庫函數。
√ 要求分離出不可移植的代碼。 例如,n 彙編代碼#ifdef SOMECODE __asm{…}n 檔案分隔字元WINDOWS平台採用的是”/”,而UNIX/linux使用的是”/”。#ifdef UNIX#define SEPERATOR ‘/’#endif#ifdef _WINDOWS||__MSDOS__#define SEPERATOR ‘//’#endifn 基本類型,不同作業系統版本對於基本類型、指標的定義是有差別的。如在64位系統上,指標是64位的。;而在32位系統上,指標是32位的。typedef char int8_t;typedef __int16 int16_t;typedef __int32 int32_t;typedef __int64 int64_t;typedef unsigned char uint8_t;typedef unsigned __int16 uint16_t; typedef unsigned int uint_t;typedef unsigned __int32 uint32_t;typedef unsigned __int64 uint64_t;#ifndef _INTPTR_T_DEFINED#ifdef _WIN64typedef __int64 intptr_t;#elsetypedef int intptr_t;#endif#define _INTPTR_T_DEFINED#endif#ifndef _UINTPTR_T_DEFINED#ifdef _WIN64typedef unsigned __int64 uintptr_t;#elsetypedef unsigned int uintptr_t;#endif#define _UINTPTR_T_DEFINED#endiftypedef intptr_t ssize_t;
√ 要求抽象應用程式依賴於平台API相關的介面。例如,對於線程的操作,linux和windows平台的API有著不同的定義。那麼我們可以把線程操作相關的介面給抽象出來,如:class Thread{public: static Thread* Create(); static Thread* CurrentThread() const; void Suspend(); void Join(); void Sleep(); void Start(); uint_t GetID() const; bool IsAlive() const; void SetPriority(int32_t priority); int32_t GetPriority() const; //...};
×
不要使用平台相關的類型或typedef,平台中立的類型或typedef。 例如, typedef VDWORD unsigned long;typedef VWORD unsigned short;DWORD value; //不好VDWORD value//好
×
不要使用移位操作符來進行指標運算。
×
不要假設在不同的平台上相同的結構(struct)具有同樣的資料長度、對齊和欄位的存放順序。 例如, struct StreamPosition { int __Size;// 不要使用__Size來記錄結構長度。 int BeginPosition;int EndPosition;};//不好StreamPosition streamPos;int begPos = *(int*)(&streamPos);