endianess-check with boost differ compared to result by small code
Hi All I am doing some preliminary checking to see whether my system is big-endian or little-endian. In LInux it should be little-endian by default, but I just wanted to double check. I used 2 appro开发者_如何学JAVAaches
- using boost endian support
- using some code I found in the web
I used the following static assertion
BOOST_STATIC_ASSERT(!BIG_ENDIAN);
that fails during compile time, so I though..mmhh...is my system big endian? This is the error I have
error: invalid application of ‘sizeof’ to incomplete type
boost::STATIC_ASSERTION_FAILURE<false>’
If I do a test using some code like the one below, it confirm that the system is little-endian. Do you know what I am doing wrong and it I am using Boost macro correctly?
bool is_big_endian_v3(){ long x = 0x34333231; char *y = (char *) &x; if(std::strncmp(y,"1234",4)){ printf("Big Endian"); return true; }else{ printf("Little Endian"); return false; } std::runtime_error ex("I cannot be here"); throw ex; }
The Boost library has changed and the code in the previous answer now (July 2019) generates deprecation messages and suggests the following:
#include <boost/predef/other/endian.h>
#include <stdlib.h>
#include <iostream>
int main()
{
#if BOOST_ENDIAN_BIG_BYTE
std::cout << "Big endian." << std::endl;
#elif BOOST_ENDIAN_LITTLE_BYTE
std::cout << "Little endian." << std::endl;
#else
std::cout << "Unknown endian." << std::endl;
#endif
exit(EXIT_SUCCESS);
}
BIG_ENDIAN
is not defined by Boost. If you look at the file
#include <boost/detail/endian.hpp>
you'll see that the macros defined there are BOOST_BIG_ENDIAN
, BOOST_LITTLE_ENDIAN
, or BOOST_PDP_ENDIAN
. That means you need to revise your check to be:
BOOST_STATIC_ASSERT(!defined(BOOST_BIG_ENDIAN));
or, better:
BOOST_STATIC_ASSERT(defined(BOOST_LITTLE_ENDIAN));
Edit:
The above is not macro expanded as I expected, so I'd suggest to use
#if !defined(BOOST_BIG_ENDIAN)
BOOST_STATIC_ASSERT(false);
#endif
instead. Sorry for the confusion.
精彩评论