Print layout of C++ object with g++ compiler

2019-01-25 09:01发布

Is there a way to print the layout of a C++ object using the g++ compiler or any other means. A simplified example (assuming int takes 4 bytes)

class A{
  int a;
};

class B:public A{
  int b;
}

so the output would be

A-
0      4
+  a   +

B-
0      4      8
+ A.a  +  b   +

It would be useful to understand the layout of objects (in my case virtual machine code).

Thanks in advance.

Regards, Zaheer

3条回答
小情绪 Triste *
2楼-- · 2019-01-25 09:09

C++ doesn't have introspection. Once your code is compiled, every piece of information about classes is lost except for what typeid and std::type_info can give you.

查看更多
神经病院院长
3楼-- · 2019-01-25 09:24

Looking at the man pages, -fdump-class-hierarchy maybe?

查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-25 09:31

The information you seek is needed by debuggers and is emitted for them when you compile with -g. On ELF/DWARF platforms (such as Linux), you can see what's there by executing:

g++ -g -c foo.cc
readelf -w foo.o

On other platforms, objdump -g foo.o may work.

For ELF/DWARF, pahole looks like a good place to start.

查看更多
登录 后发表回答