I would like to promote more of my endianness logic to compile time constexpr's. I know that in C 20, this is highly standardized via std::endian
. However, for the moment I am targeting C 17.
How can I query the target architecture's endianness from within my C code? Prefer simple constexpr functions and macros to autoconf. Would appreciate working snippets for GCC, Clang, and MSVC.
CodePudding user response:
You can use preprocessor defined macros of GCC like below
#if __BYTE_ORDER == __BIG_ENDIAN
or
#if __BYTE_ORDER == __LITTLE_ENDIAN
You've to include #include <endian.h>
header
CodePudding user response:
For a cross-platform solution you can use Boost.Predef which is a preprocessor header that even works with C. It contains various predefined macros for the target platform including the endianness (BOOST_ENDIAN_*)
#if BOOST_ENDIAN_BIG_BYTE
std::cout << "Big endian!";
#elif BOOST_ENDIAN_LITTLE_BYTE
std::cout << "Little endian!";
#endif