【问题标题】:How to output the offset of a member in a struct at compile time (C/C++)如何在编译时输出结构中成员的偏移量(C/C++)
【发布时间】:2013-06-20 15:26:20
【问题描述】:

我试图在编译期间输出结构成员的偏移量。我需要知道偏移量,稍后我想添加一个#error 以确保成员保持相同的偏移量。 我已经在 VS 中看到了几种工作方法,但我使用的是 GCC,但它们不能正常工作。

谢谢!

【问题讨论】:

  • 你应该不需要这个。你想达到什么目的?
  • 这是一个相当大的项目,其中一些是用汇编编写的,如果人们更改成员的位置,我需要让他们更难在脚上开枪,因为偏移量是硬编码的在汇编代码中。如果您知道一种从汇编代码中找到结构偏移量的方法,那可能是另一种解决方案 - 我的意思是在汇编代码中自动使用偏移量
  • 我不知道在编译时执行此操作的解决方案。但是,您可以输入几个assert(offsetof(struct foo, some_member) == 12)
  • @H2CO3:我看到了有效的用例:例如,确保外部 API 保持向后兼容......如果您检查像 ffmpeg 这样的项目,除非它是主要版本号更改,否则您不允许将成员添加到结构的中间(但您可以添加到末尾,因为这不会破坏任何内容)。
  • 可以使用 C11 静态断言吗?

标签: c++ c gcc g++


【解决方案1】:

您可以使用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" );
}

【讨论】:

    【解决方案2】:

    把它和你的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__
    

    这在你的main():

    ASSERT_OFFSETOF(foo, member, 12);
    

    即使您没有 C++11,也应该可以。如果这样做,您可以将ASSERT_OFFSETOF 定义为:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多