Check Whether System is 32-bit or 64-bit using CMake

Check Whether System is 32-bit or 64-bit using CMake

When developing software that targets multiple architectures, it's often important to determine whether the build is for a 32-bit or 64-bit system. This can influence compiler options, dependencies, or binary formats. Fortunately, CMake provides a straightforward way to check the pointer size, which reflects the platform's architecture width. This tutorial explains how to check whether a system is 32-bit or 64-bit using CMake.

CMake defines the variable CMAKE_SIZEOF_VOID_P once a compiled language (such as C or C++) is enabled in the project. This variable represents the size of a pointer on the target platform - 4 for 32-bit systems and 8 for 64-bit systems.

Here's a simple CMakeLists.txt example how to use this variable:

cmake_minimum_required(VERSION 3.27)
project(myapp)

set(CMAKE_CXX_STANDARD 17)

if (CMAKE_SIZEOF_VOID_P EQUAL 4)
    message(STATUS "32-bit")
else ()
    message(STATUS "64-bit")
endif ()

add_executable(${PROJECT_NAME} main.cpp)

In the example, 64-bit is treated as the default assumption, since the vast majority of modern desktop and server architectures are 64-bit.

Leave a Comment

Cancel reply

Your email address will not be published.