Endianness Detection with CMake

My library should read big-endian integers (4 bytes) and hide them to the final host order for processing. While on * nix ntohl worked on Windows, the use of ntohl required the use of Ws2_32.dll (Winsock).

Such a dependency is one that I would rather eliminate. The simplest way to do this seems to be to write my own switch function at the end (a trivial exercise, given that performance is not a real issue). However, this requires a way to determine the consistency of the system with which my library is compiled (so I can #ifdef execute the swap function on systems with large ends).

Since there seems to be no standard definition of the preprocessor for endianess, it looks like it needs to be defined using my build system (cmake). What is the best way to do this? (I'm tired of the “compile test file and see” solution types, since they seem to prevent cross-compilation.)

+7
endianness cmake
source share
2 answers

Edited: I see that cmake has a TestBigEndian.cmake script, but it compiles and checks to check if the system is Big Endian or not, which you don't want to do.

You can check the system entity in your own program using such a function.

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

In principle, create an integer and read its first byte (low byte). If this byte is 1, the system is of little importance, otherwise it is a big end.

However, this does not allow you to determine, until the end, before the time runs out.

If you want the compilation time to be determined by the system, I don’t see a big alternative, except for “creating a test program and then compiling my real program” a la cmake or performing exhaustive checks for certain macros defined by compilers, for example __BIG_ENDIAN__ on GCC 4. x.

UPDATED As an example, you can also take a look at Boost own endian.hpp . http://www.boost.org/doc/libs/1_43_0/boost/detail/endian.hpp

+7
source share

Also this CMake function could do this, 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 it is only supported with CMake 3.0

+6
source share

All Articles