How can I detect if I'm compiling for a 64bits architecture in C++

前端 未结 8 1706
难免孤独
难免孤独 2020-12-29 23:07

In a C++ function I need the compiler to choose a different block if it is compiling for a 64 bit architecture.

I know a way to do it for MSVC++ and g++, so I\'ll po

8条回答
  •  甜味超标
    2020-12-29 23:16

    If your using Windows, your probably better to get the "PROCESSOR_ARCHITECTURE" environment variable from the registry because sizeof(PVOID) will equal 4 if its a 32bit process running on a 64bit operating system (aka WOW64):

        if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SYSTEM\CurrentControlSet\\Control\\Session Manager\\Environment"), 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
            LPSTR szArch = new CHAR[100];
    
            ZeroMemory(szArch, 100);
    
            if (RegQueryValueEx(hKey, _T("PROCESSOR_ARCHITECTURE"), NULL, NULL, (LPBYTE)szArch, &dwSize) == ERROR_SUCCESS) {
                if (strcmp(szArch, "AMD64") == 0)
                    this->nArchitecture = 64;
                else
                    this->nArchitecture = 32;
            } else {
                this->nArchitecture = (sizeof(PVOID) == 4 ? 32 : 64);
            }
    
            RegCloseKey(hKey);
        }
    

提交回复
热议问题