2014-09-19 22 views
1

有没有办法在不实际运行代码的情况下获取特定类的所有成员变量的大小? (即没有sizeof(),offset_of()操作)获取类成员变量的大小(无需运行代码)

是否objdump或otool有一些选项可以从中间目标文件(甚至是最终的ELF文件)中提取此信息?

编辑:

“我现在想干什么?”:

我两者之间建立注意到我们的软件是一个特定的类实例的大小激增的。这个类非常大,有很多很多成员变量。有问题的类在两个构建之间没有改变,但是它的成员变量确实存在。我试图找到罪魁祸首(并且它会有点深度优先搜索,因为我必须继续深入挖掘每个成员变量,直到找到它),并且需要一个可扩展的方法来执行这无需诉诸printfs()和diffing。

+0

“无运行代码” - 阅读编译器手册? – Galik 2014-09-19 21:53:21

+1

您可以在编译时使用'sizeof',所以不需要'printf'。 – Jarod42 2014-09-19 22:15:18

回答

1

您可以创建一个基于Clang的工具来编译您的代码并在编译时转储您的类的记录布局。然后你就可以比较它们。

(也许存在用于其它编译器相似的方法为好。)

2

可以打印编译时间常数,例如不需要运行代码就可以使用sizeof。例如:

class X 
{ 
    int x; 
    int y; 
    int z; 
}; 


template <int i> 
class foo; 

foo<sizeof(X)> x; 

错误消息清楚地讲述了sizeof表达式的值:

test.cpp:12:16: error: aggregate ‘foo<12> x’ has incomplete type and cannot be defined 
foo<sizeof(X)> x; 

Works为offsetof为好。您还可以查询多个偏移一次:

#include <cstddef> 
foo<offsetof(X,X::x)> offset_x; 
foo<offsetof(X,X::y)> offset_y; 
foo<offsetof(X,X::z)> offset_z; 

结果:

test.cpp:15:23: error: aggregate ‘foo<0> offset_x’ has incomplete type and cannot be defined 
foo<offsetof(X,X::x)> offset_x; 
        ^
test.cpp:16:23: error: aggregate ‘foo<4> offset_y’ has incomplete type and cannot be defined 
foo<offsetof(X,X::y)> offset_y; 
        ^
test.cpp:17:23: error: aggregate ‘foo<8> offset_z’ has incomplete type and cannot be defined 
foo<offsetof(X,X::z)> offset_z; 
+0

是否有类似于纯C的技术(嵌入式系统,Tasking编译器 - 切换到C++不是一个选项)? – 2015-07-15 17:22:33

+0

['负数组大小'技巧](http://stackoverflow.com/questions/28332806/what-is-the-easiest-way-to-find-the-sizeof-a-type-without-compiling-and -executin/28333116#28333116)? – 2015-07-15 17:38:26

+0

或[使用预处理器](http://stackoverflow.com/questions/7168215/determine-sizeof-float-without-compilation/7171014#7171014)? – 2015-07-15 17:47:12