Check if System is Little Endian or Big Endian using CMake

Check if System is Little Endian or Big Endian using CMake

When working on cross-platform or embedded projects, you may need to know whether the target architecture is little endian or big endian. Endianness affects how multibyte data (like integers or floats) are represented in memory, which can be crucial for binary data handling, networking, or hardware interfacing. This tutorial explains how to check if a system is little endian or big endian using CMake.

If the project enables the C++ language, you can use the CMAKE_CXX_BYTE_ORDER variable to determine the target system's byte order. Here is CMakeLists.txt example:

cmake_minimum_required(VERSION 3.27)
project(myapp)

set(CMAKE_CXX_STANDARD 17)

if (CMAKE_CXX_BYTE_ORDER STREQUAL "BIG_ENDIAN")
    message(STATUS "Big endian")
else ()
    message(STATUS "Little endian")
endif ()

add_executable(${PROJECT_NAME} main.cpp)

The CMAKE_CXX_BYTE_ORDER is automatically set by CMake when the CXX language is enabled. Possible values are LITTLE_ENDIAN and BIG_ENDIAN. In the example, little endian is treated as the default assumption, since the vast majority of modern architectures use it.

If your project doesn't use C++, you can simply replace CXX with the enabled language. For example, if only C is enabled:

# ...

if (CMAKE_C_BYTE_ORDER STREQUAL "BIG_ENDIAN")
    message(STATUS "Big endian")
else ()
    message(STATUS "Little endian")
endif ()

# ...

The same pattern applies to any other language supported by CMake that defines a _BYTE_ORDER variable. You can find the full list of supported languages and their corresponding byte-order variables in the official CMake documentation.

In most environments, endianness remains consistent across all compilers, so both C and C++ typically report the same byte order. However, in more complex setups (e.g. heterogeneous toolchains) this consistency may not hold. For example, a C compiler might be configured to build code for a big endian microcontroller, while a C++ compiler targets a little endian host PC. In such cases, the values of CMAKE_C_BYTE_ORDER and CMAKE_CXX_BYTE_ORDER can differ, making per-language endianness checks necessary.

Leave a Comment

Cancel reply

Your email address will not be published.