Search code examples
c64-bitportabilityitanium

x64 compatible C source


I think I know what #ifdefs I need to use to be x86-32 and x86-64 compatible on both msvc and gcc, see below. Is this complete for those platforms?

#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

Are IA64 and x86 64 the same from a C programmer's perspective?

I'd also like to be able to compile on Macs. What do I add?

Edit: I can't use sizeof(), as I'm dealing with untouchable legacy code that use stuff like #if SIZEOF_VOIDP == SIZEOF_LONG. I am also only interested in the architectures, not the actual contents. Note that the precompiler does not allow #if sizeof(size_t) == sizeof(void*).


Solution

  • How about using your build system to generate these as constants

    #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 ;
    }
    

    Provided your build system is consistent, where everything is built with the same options, this builds in implicit portability, and you deal with the problems in your ifdefs where you've got sizeof(long) wrong on 64-bit ia64 and x64 windows (even with the gcc compiler which you've assumed to mean non-windows).

    Backing this up with the static asserts mentioned in a different answer would then give you the best of both worlds.