如何检查的结构尺寸W / O填充? [英] How to check the size of struct w/o padding?

查看:92
本文介绍了如何检查的结构尺寸W / O填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我有一个结构:

 结构A {
  uint16_t一个;
  uint64_t中B:
};

有没有一种方式来获得A的大小W / O填充?即:所有成员的sizeof(即使它不是递归)。

的总和

通常的sizeof(A)== 16。
我想 __ __ GCC_sizeof(A)== 10

我希望它在测试codeW / O影响实际code,这意味着没有#编译和没有中的结构定义__ __属性
(虽然它可以与做的#ifdef测试,但它是非常难看)。

它没有可移植的, GCC 就足够了。

谢谢!


解决方案

  

的目的是从测试内跟踪新添加的结构成员的能力。


这本来是更好的了你问这首...

和答案是肯定的,也有办法,而不是由的#include 文件;你应该使用的东西是能够获得AST / ABT结构,并列出领域则比较反对pre-注册名单。这是与铛东西可能的,例如


但现在,让我们更进一步。你为什么要测试?它是脆的!

这将是更好的测试的功能的,有什么隐藏的隐藏的一个原因。

如果每个功能是否正确测试,那么它并不重要是否只要通过测试了解字段列表。

Lets assume I have a structure:

struct A {
  uint16_t a;
  uint64_t b;
};

is there a way to get the size of A w/o padding ? i.e.: The sum of sizeof of all the members (even if it is not recursive).

Normally sizeof(A) == 16. I would like __GCC_sizeof__(A) == 10.

I want it in a test code w/o affecting the actual code, which means no "#pragma"s and no "__attribute__" in the structure definition. (Though it can be done with #ifdef TEST, but it is very ugly).

It doesn't have to be portable, GCC is enough.

Thanks!

解决方案

The purpose is the ability to track newly added structure members from inside the test.

It would have been better had you ask this first...

And the answer is yes, there are ways, but not by #include the file; you should use something that is able to get the AST/ABT structure and lists the fields then compare it against a pre-registered list. This is something possible with Clang, for example.


But now, let's go one step further. Why would you want to test that ? It's brittle!

It would be better to test functionality, what's hidden is hidden for a reason.

If each functionality is tested correctly, then it matters not whether you know the list of fields as long as the tests pass.

这篇关于如何检查的结构尺寸W / O填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆