简体   繁体   English

如何在编译时输出结构中成员的偏移量(C / C ++)

[英]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. 我正在尝试在编译时输出struct成员的偏移量。 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. 我需要知道偏移量,以后我想添加#error以确保成员保持相同的偏移量。 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. 在VS中,我已经看到了几种方法可以做到这一点,但是我正在使用GCC,但它们无法正常工作。

Thanks! 谢谢!

You can use the offsetof macro, along with the C++11 static_assert feature, such as follows: 您可以将offsetof宏与C ++ 11 static_assert功能一起使用,如下所示:

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() : 将此与您的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() : 这在你的main()

ASSERT_OFFSETOF(foo, member, 12);

That should work even if you don't have C++11. 即使您没有C ++ 11,也应该可以使用。 If you do, you can just define ASSERT_OFFSETOF as: 如果这样做,则可以将ASSERT_OFFSETOF定义为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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