How do I determine the native endian at compile time?

Asked 2 months ago, Updated 2 months ago, 5 views

At runtime, you can determine if the native endian is a little endian, for example:

#include<iostream>

const int bomb = 1;
bool is_little_endian(){
    return*reinterpret_cast<const char*>(&bom)==1;
}

int main()
{
    const pool b=is_little_endian();
    std::cout<<b<<'\n';
}

C++11 added a constant expression function (constexpr), so I thought that if I changed const to constexpr, I could make a decision at the time of compilation, but reinterpret_cast doesn't seem to work in constant expressions, resulting in a compilation error.

#include<iostream>

constexprint bomb = 1;
constexprbool is_little_endian(){
    return*reinterpret_cast<const char*>(&bom)==1;
}

int main()
{
    constexpr bool b=is_little_endian();
    std::cout<<b<<'\n';
}

;

#clang++-Wall-std=c++11 test_endian.cpp
test_endian.cpp:4:16:error:constexpr function never produce a constant
      expression [-Winvalid-constexpr]
constexprbool is_little_endian(){
               ^
test_endian.cpp:5:10:note:reinterpret_cast is not allowed in a constant
      expression
        return*reinterpret_cast<const char*>(&bom)==1;
                ^
1 error generated.

I think the native endian has been decided at the time of compilation, so I would like to make a decision at the time of compilation, but is there any other way besides using the compiler's own macro like Boost library?

リトルIt would be best if you could categorize it into Little Endian/Big Endian/Other, not just Little Endian or not.

■Additional
The purpose is to optimize the implementation of external data endian-native endian relationships when creating functions/classes that convert external and internal data.

c++ c++11

2022-09-30 11:36

2 Answers

As yoh2's comment, the constexpr function as of C++14 cannot determine the endian at compile time.All similar questions from the head office SO answered no.

If you are in an environment where you can use Boost Library, I think the following would be convenient.Both are header-only libraries available from C++03.

Note:It's still a quick story before the official publication of C++17, but future C++ standard libraries (C++20) will include std:endian for native endian decisions at compile time.

//require C++20
# include<type_trites>
constexprbool is_little_endian(){
    return std::endian::native==std::endian::little;
}

(via https://www.reddit.com/r/cpp/comments/6ngkgc/2017_toronto_iso_c_committee_discussion_thread/)


2022-09-30 11:36

I'm not sure if it's standard or not, but there's something called endian.h in CentOS like /usr/include/machine/bottom like /usr/include/machine/bottom.

#include<machine/endian.h>

# if__BYTE_ORDER ==_LITTLE_ENDIAN
...
#elif__BYTE_ORDER==_BIG_ENDIAN
...
#endif


2022-09-30 11:36

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.