0

We want to write endian-independent code in C using some preprocessor directive. Can we define a preprocessor directive which will help us to check endianness of the machine during compile time? We want something like below sample code. Any help would be appreciated.

#if(some conditions)
#define LITTLE_ENDIAN 1
#else
#define LITTLE_ENDIAN 0
#endif

I know there are several solutions but those are not fulfilling my requirement. I don't want to compile little endian specific code in a big endian machine and the vice versa. For example

#if LITTLE_ENDIAN

 line1..
 line2..
 line3..

#else

 line4..
 line5..
 line6..

#endif

In big endian machine I don't want to compile lines 1,2 and 3. Those three lines should be disabled.

  • 1
    If you program in C, then please only add the C tag (even if the problem might be applicable to both C and C++). Especially, don't add a version-specific language tag (like `c++14`) unless your question is about that specific version of the language. – Some programmer dude Oct 11 '17 at 06:03
  • As for your problem, there are *many* open-source projects out there that have the same need, and which have solved it. Try looking around a little. – Some programmer dude Oct 11 '17 at 06:05
  • @Someprogrammerdude I found some solution but those are not for compile time checking. Please share the solution. – Sougata Laha Oct 11 '17 at 06:10
  • 1
    The way I would solve it would be to use my favorite search engine and look for existing solutions. Adding the word `preprocessor` or `compile time` is important if that's what you want. And reading the documentation of my compiler (it might already have macros for it). – Some programmer dude Oct 11 '17 at 06:14
  • would you please share the solution here. It would be really helpful for me. – Sougata Laha Oct 11 '17 at 12:20
  • Please, remove C++14 tag. You can do it at compile time and remove unnecessary code with `if constexpr` (C++17) without preprocessor usage in a portable way. And as mentioned most of the compilers do have a macro ready for you. – Sergey.quixoticaxis.Ivanov Oct 13 '17 at 17:12

1 Answers1

0

I am not sure it is possible. I was using CMake in Android NDK, and there was a CMake widget to perform this test.

Unfortunately, it ran on the host (windows) computer, rather than understood the target (android) device.

There needs to be a published mechanism (e.g. compiler provided value) for this to work correctly, and I am not aware of any such global values.

Adding link to potential duplicate SO : detect endianness. Some methods there look plausible.

mksteve
  • 12,614
  • 3
  • 28
  • 50