Skip to content
systemcoding.dev
Fundamentals

Detect endianness at compile time with __BYTE_ORDER__

Test __BYTE_ORDER__ against __ORDER_LITTLE_ENDIAN__ in the preprocessor with GCC 4.6 or Clang, so byte order is a build-time fact instead of a runtime probe.

1 min read
Summarize in AI

Probing byte order at run time by casting an int to a char pointer works, but it turns a fixed property of the target into a branch. GCC and Clang predefine __BYTE_ORDER__ and the constants to compare it against, so the preprocessor can decide, and a wrong guess becomes a build error instead of a corrupt file.

endian.cc
#include <stdio.h>

#if !defined(__BYTE_ORDER__) || !defined(__ORDER_LITTLE_ENDIAN__)
#error "compiler does not define __BYTE_ORDER__"
#endif

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define HOST_NAME "little-endian"
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define HOST_NAME "big-endian"
#else
#error "unsupported byte order"
#endif

int main(void) {
    puts(HOST_NAME);
    return 0;
}
Text
little-endian

That output is for x86-64 and 64-bit Arm Linux. GCC 4.6 and later and current Clang document the macros under common predefined macros. A third value, __ORDER_PDP_ENDIAN__, exists for mixed-order machines, which is why the chain ends in an #error rather than an assumption. MSVC does not define these macros, so a portable header needs a second branch keyed on _MSC_VER; MSVC targets are all little-endian.

Taggedcgcc
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.