简体   繁体   中英

How to output the offset of a member in a struct at compile time (C/C++)

I'm trying to output the offset of a struct member during compile time. I need to know the offset and later I'd like to add an #error to make sure the member stays at the same offset. There are a couple of ways I saw working methods to do that already in VS, but I'm using GCC and they didn't work properly.

Thanks!

You can use the offsetof macro, along with the C++11 static_assert feature, such as follows:

struct A {
     int i;
     double db;
     ...
     unsigned test;
};

void TestOffset() {
     static_assert( offsetof( A, test ) == KNOWN_VALUE, "The offset of the \"test\" variable must be KNOWN_VALUE" );
}

put this in the same file as your main() :

template <bool> struct __static_assert_test;
template <> struct __static_assert_test<true> {};
template <unsigned> struct __static_assert_check {};

#define ASSERT_OFFSETOF(class, member, offset) \
    typedef __static_assert_check<sizeof(__static_assert_test<(offsetof(class, member) == offset)>)> PROBLEM_WITH_ASSERT_OFFSETOF ## __LINE__

and this inside your main() :

ASSERT_OFFSETOF(foo, member, 12);

That should work even if you don't have C++11. If you do, you can just define ASSERT_OFFSETOF as:

#define ASSERT_OFFSETOF(class, member, offset) \
    static_assert(offsetof(class, member) == offset, "The offset of " #member " is not " #offset "...")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM