C++ compile type endianness for use in macros
16:17 24 Nov 2025

I need to layout a structure in two different ways depending on the endianness of the target platform. Currently I'm using an additional pre-compile phase to run a program to test the endianness, and define macros that can be used thus:

struct {
#if MACH_BYTE_ORDER_LSB
    Byte            a;
    Byte            b;
#else
    Byte            b;
    Byte            a;
#endif
};

I'd really like to get rid of this pre-compile phase.

While C++20 introduced std::endian in the header, this only appears to be of use for run-time tests, and in static_assert compile-time tests.

Is there a way I can use this from within the C++ pre-processor instead, or otherwise change my structure layout to put the fields in the right order? AFAIK there's no standard-defined macro that I can rely upon to exist in every C++20 compatible compiler.

c++ std c++20 c-preprocessor endianness