0

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.

phuclv
  • 32,499
  • 12
  • 130
  • 417
mcandre
  • 20,703
  • 18
  • 81
  • 144
  • Have you read the documentation for the compilers you mention? Especially what preprocessor macros they might define for identifying the target system? – Some programmer dude Oct 13 '21 at 15:57
  • Related to [c-macro-definition-to-determine-big-endian-or-little-endian-machine](https://stackoverflow.com/questions/2100331/c-macro-definition-to-determine-big-endian-or-little-endian-machine). – Jarod42 Oct 13 '21 at 16:04
  • 1
    https://stackoverflow.com/a/40675229/9072753 what research did you do? – KamilCuk Oct 13 '21 at 17:09

2 Answers2

0

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

Harry
  • 1,757
  • 1
  • 14
  • 28
0

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
phuclv
  • 32,499
  • 12
  • 130
  • 417