Print layout of C++ object with g++ compiler
Asked Answered
P

3

14

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

Pacemaker answered 5/6, 2010 at 7:49 Comment(0)
T
12

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

Note that since GCC 8, the -fdump-class-hierarchy option has been replaced with -fdump-lang-class.

Tensible answered 5/6, 2010 at 8:7 Comment(1)
This is an option of g++ (gcc.gnu.org/onlinedocs/gcc-6.2.0/gcc/Developer-Options.html), although I am not sure why my g++ doesn't recognize it.Bernardo
V
4

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.

Virginity answered 7/6, 2010 at 3:4 Comment(0)
F
1

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.

Fill answered 5/6, 2010 at 7:59 Comment(1)
I don't think he's talking about runtime introspection, but about some compiler option that is able to tell him about the memory layout chosen by the compiler for the objects in his code.Anstus

© 2022 - 2024 — McMap. All rights reserved.