Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant and safe way to determine if architecture is 32bit or 64bit

As title says, is there any elegant and safe way to determine if architecture is 32bit or 64bit. By elegant, you can think of precise, correct, short, clean, and smart way. By safe, think of safe in term of standard, C89/C99, and operating system independence.

like image 836
mtasic85 Avatar asked Aug 17 '09 14:08

mtasic85


2 Answers

short answer: no

long answer: it depends on too many OS/compiler combinations. For example at runtime, on linux you can query the proc filesystem whereas on windows you can query the register.

You can prove that the compiler that are being used for compilation has a 32/64 bits target using something like:

bool is_32bit() {
    return sizeof(int *) == 4;
} 

bool is_64bit() {
    return sizeof(int *) == 8;
} 

this could works under few assumptions (e.g. it works at runtime). You can search for compile-time #define for your platform but it is a well-known mess.

like image 139
dfa Avatar answered Oct 20 '22 00:10

dfa


If you are using GCC (as indicated in the tags), you can test, as a compile-time test

#if __SIZEOF_POINTER__ == 8

to find out whether it's a 64-bit system. Make sure the GCC version you are using defines __SIZEOF_POINTER__ at all before using it.

like image 29
Martin v. Löwis Avatar answered Oct 19 '22 23:10

Martin v. Löwis