简体   繁体   中英

32-bit or 64-bit? Using C code

有没有办法通过在C中写入一些代码来确定机器是32位还是64位?

#include <limits.h>
/* ... */
printf("This machine's pointers to void, in a program "
       "compiled with the same options as this one and "
       "with the same compiler, use %d bits\n",
    (int)sizeof (void*) * CHAR_BIT);

If by "some code in C" you mean standard C code, then the answer is no, it is not possible. For a C program, the "world" it can see is created entirely by the implementation (by the compiler). The compiler can emulate absolutely any "world", completely unrelated to the underlying hardware.

For example, you can run a 32-bit compiler on a 64-bit machine and you will never be able to detect the fact that this is a 64-bit machine from your program.

The only way you can find out anything about the machine is to access some non-standard facilities, like some OS-specific API. But that goes far beyond the scope of C language.

Needless to add, the already suggested in other answers methods based on sizeof and other standard language facilities do not even come close detect the bit-ness of the machine. Instead they detect the bit-ness of the platform provided by the compiler implementation, which in general case is a totally different thing.

There is no such thing as 32 bit or 64 bit environments, this is just too much of an oversimplification. You have several characteristics of integer, pointer, and float sizes that come into play if you want to write a portable application.

The size of your different integer types can be checked with the appropriate macros such as UINT_MAX etc, pointer size by UINTPTR_MAX . Since there might be padding bits, to deduce the width of the types you should print something like (unsigned long long)(T)-1 where T is an unsigned type.

The pointer size

sizeof (void *) * CHAR_BIT

is a good indicator, but might be misleading on more exotic architectures (eg if the size of the address bus is no multiple of the word size) and only represent the execution environment (which might be different from the actual hardware - see AndreyT's answer ).

During the preprocessing phase, the best you can do within the framework of the C language is something like

UINTPTR_MAX == UINT64_MAX

The same limitations as above apply.

Yes, if running on an x86 processor use the CPUID instruction:

http://en.wikipedia.org/wiki/CPUID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM