C++設計開發規範(6):移植性設計規範

來源:互聯網
上載者:User
 

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);

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.