User:Monster Iestyn/Source Code Documentation/endian.h

From SRB2 Wiki
Jump to navigation Jump to search
Online link GitHub entry
File type C header file
#include guard __ENDIAN__

This header file detects the endianness of the processor that SRB2 is compiled with, and defines the appropriate macro for it (see below). Other files in SRB2's source code that include endian.h can then use these macros to determine whether to compile big-endian or little-endian specific code. (However, this is only done in m_swap.h and md5.h as of the latest release of SRB2.)

Includes

Macros

Macro Description
SRB2_LITTLE_ENDIAN Defined if Little-endian; undefined otherwise
SRB2_BIG_ENDIAN Defined if Big-endian; undefined otherwise

Example usage:

#if SRB2_BIG_ENDIAN

// Big-endian specific code

#else

// Little-endian specific code

#endif

Detection

In order to define either of the two endianness macros, endian.h has to detect the endianness of the processor itself. The method of endianness detection used depends on the operating system or compiler used when compiling SRB2:

  • On FreeBSD, the value of the macro _BYTE_ORDER is checked – here, _BIG_ENDIAN and _LITTLE_ENDIAN are constants to compare _BYTE_ORDER to, rather than flags.
    • _BYTE_ORDER == _BIG_ENDIANSRB2_BIG_ENDIAN is defined
    • _BYTE_ORDER != _BIG_ENDIANSRB2_LITTLE_ENDIAN is defined
  • If the macro __BYTE_ORDER__ is defined, the value of it is checked – in particular, this macro is provided by compilers such as GCC (from GCC 4.6 onwards) or Clang. Possible values for this macro are: __ORDER_LITTLE_ENDIAN__, __ORDER_BIG_ENDIAN__ or __ORDER_PDP_ENDIAN__[1].
    • __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__SRB2_BIG_ENDIAN is defined
    • __BYTE_ORDER__ != __ORDER_BIG_ENDIAN__SRB2_LITTLE_ENDIAN is defined
  • Otherwise, if the two cases above do not apply, the compiler checks if _BIG_ENDIAN is defined or not:
    • _BIG_ENDIAN is defined → SRB2_BIG_ENDIAN is defined
    • _BIG_ENDIAN is not defined → SRB2_LITTLE_ENDIAN is defined

References