No more autoconf for endianess detection - Journal of Omnifarious

Sep. 10th, 2009

08:27 am - No more autoconf for endianess detection

autoconf is annoying to work with, and I think that programs that rely excessively on it for cross platform compatibility have issues of their own. Sometimes you really have no choice though.

Fortunately I recently discovered one place where I now do have a choice where I didn't before. This little code snippet can be optimized by gcc at compile time into a constant expression. That means that gcc realizes there is only one possible result and it uses that result in place of actually running the code in the function. Here is the code snippet:

gcc will be smart enough to see that only one branch of that if will ever be taken and optimize the other completely out of your code.

Normally you'd want to use autoconf for this so you will have a preprocessor macro that will elide the code for you. The fact gcc can optimize this well means you don't have to do that to get efficient code.

*chuckle* Well, yes. And just because 0x44u is first doesn't mean that 0x33u is next, so do_something() could have problems too. That code only covers 99.9% of the hardware out there. I'm sure there are some strange byte orders lurking around somewhere.

I could test explicitly (and fully) for one byte ordering or the other and throw an exception if it was neither. It would be interesting to see if gcc could optimize that sufficiently.