x64兼容C源

Jon*_*röm 0 c 64-bit portability itanium

我想我知道我需要使用的#ifdefs在msvc和gcc上兼容x86-32和x86-64,见下文.这些平台是否完整?

#if defined(_MSC_VER)
#  if defined(_M_IA64) || defined(_M_X64)
#    define SIZEOF_SIZE_T 8
#    define SIZEOF_VOIDP  8
#  elif defined(_M_IX86)
#    define SIZEOF_SIZE_T 4
#    define SIZEOF_VOIDP  4
#  else
#    error "Unsupported MSVC platform"
#  endif
#elif defined(__GNUG__)
#  if defined(__x86_64__) || defined(__ia64__)
#    define SIZEOF_SIZE_T 8
#    define SIZEOF_VOIDP  8
#  elif defined(__i386__)
#    define SIZEOF_SIZE_T 4
#    define SIZEOF_VOIDP  4
#  else
#    error "Unsupported GCC platform"
#  endif
#endif
Run Code Online (Sandbox Code Playgroud)

从C程序员的角度来看,IA64和x86 64是否相同?

我也希望能够在Mac上编译.我要添加什么?

编辑:我不能使用sizeof(),因为我正在处理使用类似东西的不可触摸的遗留代码#if SIZEOF_VOIDP == SIZEOF_LONG.我也只对架构感兴趣,而不是实际内容.请注意,预编译器不允许#if sizeof(size_t) == sizeof(void*).

Pee*_*oot 6

如何使用构建系统生成这些常量

#include <stdio.h>

int main()
{
   printf(
      "#if !defined ARCH_MODEL_CONSTANTS_H\n"
      "#define ARCH_MODEL_CONSTANTS_H\n"
      "\n"
      "#    define SIZEOF_LONG  %u\n"
      "#    define SIZEOF_VOIDP %u\n"
      "\n"
      "#endif\n",
      (unsigned)sizeof(long),
      (unsigned)sizeof(void *) ) ;

   return 0 ;
}
Run Code Online (Sandbox Code Playgroud)

前提是你的编译系统是一致的,这里的一切都使用相同的选项建,这样做可以在隐便携性,你应对你的问题ifdef是你要重得sizeof(long)错误在64位IA64和x64窗口(甚至与海湾合作委员会您假设非Windows的编译器).

使用不同答案中提到的静态断言来支持这一点将为您提供两全其美的优势.