Is there a way to do a C++ style compile-time assertion to determine machine's endianness?

If you're using autoconf, you can use the AC_C_BIGENDIAN macro, which is fairly guaranteed to work (setting the WORDS_BIGENDIAN define by default)

alternately, you could try something like the following (taken from autoconf) to get a test that will probably be optimized away (GCC, at least, removes the other branch)

int is_big_endian()
{
    union {
        long int l;
        char c[sizeof (long int)];
    } u;

    u.l = 1;

    if (u.c[sizeof(long int)-1] == 1)
    {
        return 1;
    }
    else
        return 0;
}

There is no portable way to do this at compile time, your best bet is probably to use the Boost endian macros or emulate the methods they use.


Hmm, that's an interesting Question. My bet is that this is not possible. I think you have to continue using macros, and go with BOOST_STATIC_ASSERT(!BIG_ENDIAN);, or static_assert in c++0x. The reason i think this is because the endian'nes is a property if your execution environment. However, static_assert is considered at compile time.

I suggest you look into the code of the new GNU gold ELF linker. Ian Lance Taylor, its author, used templates to select the right endianness at compile time, to ensure optimal performance at run time. He explicitely instantiates all possible endians, so that he still has separate compilation (not all templates in headers) of the template definition and declaration. His code is excellent.