Detect Endianness with CMake

Edited: I see that cmake has a TestBigEndian.cmake script, but that does a compilation and test run to see if the system is Big Endian or not, which is not what you want to do.

You can check for the system's endianness in your own program with a function like this.

bool isLittleEndian()
{
    short int number = 0x1;
    char *numPtr = (char*)&number;
    return (numPtr[0] == 1);
}

Basically create an integer, and read its first byte (least significant byte). If that byte is 1, then the system is little endian, otherwise it's big endian.

However this doesn't allow you to determine endianness until runtime.

If you want compilation time determination of system endianness, I do not see much alternative aside from the 'building a test program and then compile my real program' a la cmake, or doing exhaustive checks for specific macros defined by compilers, e.g. __BIG_ENDIAN__ on GCC 4.x.

UPDATED You might want to take a look at Boost's own endian.hpp as an example, too. http://www.boost.org/doc/libs/1_43_0/boost/detail/endian.hpp


Also this CMake function could do it, http://www.cmake.org/cmake/help/v3.5/module/TestBigEndian.html

include (TestBigEndian)
TEST_BIG_ENDIAN(IS_BIG_ENDIAN)
if(IS_BIG_ENDIAN)
 message(STATUS "BIG_ENDIAN")
else()
 message(STATUS "LITTLE_ENDIAN")
endif()

I think that is supported only from CMake 3.0