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

后端 未结 7 1591
北恋
北恋 2021-01-19 01:47

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.

7条回答
  •  甜味超标
    2021-01-19 02:16

    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.

提交回复
热议问题