#ifdef for 32-bit platform

后端 未结 11 1423
眼角桃花
眼角桃花 2020-12-30 00:37

In an application I maintain, we\'ve encountered a problem with file descriptor limitations affecting the stdlib. This problem only affects the 32-bit version of the standar

相关标签:
11条回答
  • 2020-12-30 00:52

    I would test it indirectly, via the maximum pointer value constant:

    #include <stdint.h>
    
    #if UINTPTR_MAX == 0xffFFffFF
    // 32-bit platform
    #elif UINTPTR_MAX == 0xffFFffFFffFFffFF
    // 64-bit platform
    #else
    #error Unknown platform - does not look either like 32-bit or 64-bit
    #endif
    

    This way you don't rely on any platform-specific define for architecture, but on the direct consequence of having a specific architecture - the pointer size.

    0 讨论(0)
  • 2020-12-30 00:56

    What I would probably end up doing, is within a Makefile, determine if you are on a 32 bit platform or 64 bit using uname. Then, add to your CFLAGS, -DX32, or -DX64. That you could just #ifdef X64.

    But this is just a unixy solution. I'm not sure what I would do on windows.

    0 讨论(0)
  • 2020-12-30 00:56

    Depends on your OS and compiler, those are implementation decisions.

    0 讨论(0)
  • 2020-12-30 00:57

    I recommend bookmarking the predef SourceForge. There's no one answer, but it can certainly help you get started.

    EDIT: For GCC-only code, you can use __i386__ to check for 32-bit x86 chips, and I suggest trying __X86_64__ or something similar to check for 64-bit x86 chips. (Note: It has come to my attention that the previous answer involving __ia86__ is actually a different chip, not a 64-bit x86 chip. This just shows my lack of hardware experience. For those more knowledgeable about hardware than I, consule the SourceForge page on predefined macros that I link to above. It's much more accurate than I am.) There are some other ones that would work, but those two should be fairly universal amongs GCC versions.

    0 讨论(0)
  • 2020-12-30 00:58

    Have a look at that:

    i386 macros
    AMD64 macros

    0 讨论(0)
  • 2020-12-30 00:59

    You could check a well known type for it's size e.g. sizeof(int*) == 4 for a 32 bit platform.

    As sizeof is known at compiletime I believe a

    if(sizeof(int*) == 4)
    {
      ...
    }
    

    should do the trick

    Edit: the comments are right, you need to use a regular if, #if won't work.

    If you are using C++ You could create templated code and let the compiler choose the specialization for you based on the sizeof() call. If you build for a 32 bit platform the compiler would only instantiate the code for the 32 bit platform. If you build for a 654 bit platform the compiler would only instantiate the code for the 64 bit platform.

    0 讨论(0)
提交回复
热议问题