Reed
Reed

Reputation: 519

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!

Upvotes: 1

Views: 1827

Answers (2)

Massa
Massa

Reputation: 8972

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 "...")

Upvotes: 2

Thomas Russell
Thomas Russell

Reputation: 5980

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" );
}

Upvotes: 6

Related Questions