简体   繁体   English

如何可视化 C++ 结构/类的布局

[英]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?可视化由 GCC 编译的 C++ 类/结构的 memory 布局的最佳方法是什么?

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 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.我只想查看类/数据成员的大小/偏移量。

You can use pahole.你可以使用pahole。 It is a swiss army tool for this kind of things.这是处理这类事情的瑞士军队工具。

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

For example, say you have this test.cpp file例如,假设你有这个 test.cpp 文件

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(带有调试信息)

$ 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您还可以使用-C <classname>参数提供 class 名称

$ 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 */
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM