c++gccstructvisualizationmemory-layout

How to visualize layout of C++ struct/class


What is the best way to visualize the memory layout of a C++ class/struct, compiled by GCC?

I added the GCC switch -fdump-lang-class to my C++ compile options but it didn't output anything to stdout, nor did I notice any files .class files created.

I just want to see the size/offsets of class/data members.


Solution

  • You can use pahole. It is a swiss army tool for this kind of things.

    https://manpages.ubuntu.com/manpages/impish/man1/pahole.1.html

    For example, say you have this test.cpp file

    struct A {
            int i;
            char c;
            double x;
    };
    
    void doit( A& a ) {
            a.i = 1;
            a.c = 0;
            a.x = 1.0;
    }
    

    Let's compile it into a shared library

    $ g++ test.cpp -shared -ggdb -o libtest.so
    $ ls -l libtest.so
    -rwxrwxr-x 1 awesome awesome 16872 Aug 12 20:15 libtest.so
    

    Then run pahole on the binary (with debug information)

    $ pahole libtest.so
    struct A {
            int                        i;                    /*     0     4 */
            char                       c;                    /*     4     1 */
            /* XXX 3 bytes hole, try to pack */
            double                     x;                    /*     8     8 */
    
            /* size: 16, cachelines: 1, members: 3 */
            /* sum members: 13, holes: 1, sum holes: 3 */
            /* last cacheline: 16 bytes */
    };
    

    You can also provide a class name with the -C <classname> argument

    $ pahole -C A libtest.so
    struct A {
            int                        i;                    /*     0     4 */
            char                       c;                    /*     4     1 */
            /* XXX 3 bytes hole, try to pack */
            double                     x;                    /*     8     8 */
    
            /* size: 16, cachelines: 1, members: 3 */
            /* sum members: 13, holes: 1, sum holes: 3 */
            /* last cacheline: 16 bytes */
    };