How do I dump an arbitrary struct in C?

后端 未结 4 1072
日久生厌
日久生厌 2021-01-12 03:07

I don\'t know which direction to go,perhaps something like reflection will help?

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-12 03:56

    If you're using Clang 8 or newer, you can now use the built-in compiler function __builtin_dump_struct to dump a struct. It uses the information that's naturally available at compile time to generate code that pretty-prints a struct.

    Example code demonstrating the function:

    dumpstruct.c:

    #include 
    
    struct nested {
        int aa;
    };
    
    struct dumpme {
        int a;
        int b;
        struct nested n;
    };
    
    int main(void) {
        struct nested n;
        n.aa = 12;
        struct dumpme d;
        d.a = 1;
        d.b = 2;
        d.n = n;
        __builtin_dump_struct(&d, &printf);
        return 0;
    }
    

    Example compile-and-run:

    $ clang dumpstruct.c -o dumpstruct
    $ ./dumpstruct 
    struct dumpme {
    int a : 1
    int b : 2
    struct nested n : struct nested {
        int aa : 12
        }
    }
    

    If you're not using Clang >= 8 but you are using GCC, it's pretty easy to switch. Just install the clang-8 or clang-9 package and replace invocations of gcc with clang.

提交回复
热议问题