跨平台 C 语言开发

  1. 通过 WIN32 宏来判断是否为 Windows 平台。64位 Windows 也会定义 WIN32 宏,此外还定义 WIN64 宏,有些编译器可能是 Windows__WIN32__WIN32_WIN64
  2. 通过 _MSC_VER 宏判断是否是VC编译器
  3. 通过 __GNUC__ 宏来判断是否为 gcc 编译器
  4. Windows 平台上的 gcc 编译器支持__declspec(dllimport)__declspec(dllexport)
  5. Linux 平台上 gcc 通过 __attribute__ ((visibility("default"))) 来导出函数
  6. VC不支持 inline 关键字,要用 __inline。可以用如下代码定义:
    C#if defined(_MSC_VER) && !defined(__cplusplus) && !defined(inline)
        #define inline __inline
    #endif
  7. 数组索引用 size_t 类型、指针运算用 uintptr_t, intptr_t, ptrdiff_t、平台无关整型用 int32_t, int64_t
  8. 64位平台上的 sizeof(long double) 是16字节(VC不支持),但是实际使用长度是12字节,4字节填充的是随机数据(绝对大坑)
  9. 如果 C 代码可能被 C++ 项目使用,最好根据 __cplusplus 宏做下判断
  10. MacOSX的平台宏是 __APPLE____MACH__(这个没确认)
  11. 补充几个编译器识别的宏:__BORLANDC____llvm____clang____WATCOMC__

Predefined macros in C/C++ that tell you what the target platform is. Predefined macros in C/C++ that tell you what the target platform is

Predefined macros in C/C++ that tell you what the compiler is. Predefined macros in C/C++ that tell you what the compiler is

Non-model-specific macros that describe the processor in terms of its features Non-model-specific macros that describe the processor in terms of its features

Predefined macros in C/C++ that tell you what language features are available Predefined macros in C/C++ that tell you what language features are available

Macros that are specific to Intel Architecture processor targets Macros that are specific to Intel Architecture processor targets

Macros for other than Intel Architecture processor targets Macros for other than Intel Architecture processor targets