Where is the macro LITTLE_ENDIAN_HOST and how does it behave?

Asked

Viewed 26 times

0

After finally understanding how the decoding of opcodes works with a project of a CHIP-8 emulator I decided to return to an old project of mine, an emulator of Gameboy, so I started to implement the CPU and its registers, the CPU of Gameboy is similar to the 8080 and the Z80, The Gameboy has 6 16-Bit registers and most are formed by the junction of 2 8-Bit registers as indicated by this documentation.

I came to a point where I needed to decrement the register B which would be the highest end of BC, I thought of using the bit shift operator but would probably erase the value of C, then talking in a Discord group related to Gameboy development of how I could do that a member presented me the following code:

    typedef union RegPair{

        std::uint16_t value;
        struct byte{

#ifndef LITTLE_ENDIAN_HOST
            std::uint8_t l, h;
#else
            std::uint8_t h, l;
#endif // !LITTLE_ENDIAN_HOST


        }b;

    }RegPair;

    struct Registers {

        RegPair AF, BC, DE, HL;

        std::uint16_t SP;    // Stack Pointer
        std::uint16_t PC;    // Program Counter

    };

That was even easy to understand, as value has the most significant type in marriage so h and l would assume part of this value, but the question is LITTLE_ENDIAN_HOST certainly this refers to the type of end of the machine, what I do not understand is:

Macros are for the compiler and not for the code, as I checked that my machine is Little Endian so the program would be mounted as little endian, so it would run on a Big Endian computer?

And where is the definition of this macro? I googled but only find snippets of code but no site explaining its definition, in which header it is set etc...

1 answer

0


LITTLE_ENDIAN_HOST certainly is inherent to some specific project and indicates if the program is being compiled on an architecture little-endian, and is not part of the standard C.

It’s a very common technique to keep a good portabilidade of the code, that is, allowing the same code to be compiled and executed in different environments and architectures.

Certainly LITTLE_ENDIAN_HOST is defined by the user during the code/project compilation step.

Conditional stretches of the type:

#ifndef LITTLE_ENDIAN_HOST
            std::uint8_t l, h;
#else
            std::uint8_t h, l;
#endif // !LITTLE_ENDIAN_HOST

Decide how the implementation/behavior of the program will be depending on the Endianess of the architecture in which it will be executed, and therefore has no effect on runtime.

  • Well, if it is defined in the project then this condition would not affect since it will always be called correct Else?

  • In the case, the else would be a compilation for architecture little-endian.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.