As the title says, is there an elegant and secure way to determine if an architecture is 32-bit or 64-bit. Thanks to elegance, you can think in a precise, correct, short, clean and smart way. Safe, think about security in terms of standard, C89 / C99 and operating system independence.
The size of the pointers is actually not very well checked - there is not much in the C standard that you can do with the result of this test.
- ((size_t)-1), , C:
((size_t)-1)
if ((size_t)-1 > 0xffffffffUL) { printf("> 32 bits\n"); } else { printf("<= 32 bits\n"); }
, 0xffffffffUL, 2**32 - 1 , , "32 64 ".
0xffffffffUL
2**32 - 1
(, , size_t - 2**32 - 1, mmap() 1 2 .)
size_t
mmap()
:
: OS/. , linux proc, .
, , , 32/64 , - :
bool is_32bit() { return sizeof(int *) == 4; } bool is_64bit() { return sizeof(int *) == 8; }
(, ). #define , .
#define
GCC ( ), ,
#if __SIZEOF_POINTER__ == 8
, 64- . , GCC __SIZEOF_POINTER__ , .
__SIZEOF_POINTER__
sizeof(void*) sizeof(int) ( , ).
sizeof(void*)
sizeof(int)
x86/x64 - "lm". , CPU AMD64.
, , ( C).
sizeof(int) 4 32- 8 64- , . C , int "" , sizeof (int) 4 64- , "",.
sizeof(void*) , . sizeof(void*) , , 4 8, . , , sizeof , -, 8 . - , , , 8 , . 8- , , 16- 16- ( sizeof(int) 1). , 8 , sizeof(void*) .
, x86 x64 (32- 64- ), sizeof (void *) .
32- 32- .:-) 8086 16- 20- . , Havard /...
cpuid x86. ... YMMV.
cpuid
int iedx; __asm { mov eax, 0x80000001; cpuid; mov, iedx,edx; } if (iedx & (1 << 29)) { return 1; } return 0;