C++设计开发规范(6):移植性设计规范

    技术2022-05-11  22

    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                 ‘//’ #endif n 基本类型,不同操作系统版本对于基本类型、指针的定义是有差别的。 如在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 _WIN64 typedef      __int64 intptr_t; #else typedef      int intptr_t; #endif #define _INTPTR_T_DEFINED #endif #ifndef _UINTPTR_T_DEFINED #ifdef _WIN64 typedef unsigned __int64 uintptr_t; #else typedef unsigned int uintptr_t; #endif #define _UINTPTR_T_DEFINED #endif typedef 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);  

    最新回复(0)