Is there a way to determine a member offset at compile time?

后端 未结 3 480
没有蜡笔的小新
没有蜡笔的小新 2020-12-19 15:57

I\'m finding I\'m spending a lot of time trying to determine member offsets of structures while debugging. I was wondering if there was a quick way to determine the offset

3条回答
  •  时光说笑
    2020-12-19 16:43

    offsetof is what you want for this and it compile time. The C99 draft standard section 7.17 Common definitions paragraph 3 says:

    offsetof(type, member-designator)

    which expands to an integer constant expression that has type size_t, the value of which is the offset in bytes [...]

    the man pages linked above has the following sample code, which demonstrates it's usage:

    struct s {
        int i;
        char c;
        double d;
        char a[];
    };
    
    /* Output is compiler dependent */
    
    printf("offsets: i=%ld; c=%ld; d=%ld a=%ld\n",
            (long) offsetof(struct s, i),
            (long) offsetof(struct s, c),
            (long) offsetof(struct s, d),
            (long) offsetof(struct s, a));
    printf("sizeof(struct s)=%ld\n", (long) sizeof(struct s));
    

    sample output, which may vary:

     offsets: i=0; c=4; d=8 a=16
     sizeof(struct s)=16
    

    For reference constant expressions are covered in section 6.6 Constant expressions and paragraph 2 says:

    A constant expression can be evaluated during translation rather than runtime, and accordingly may be used in any place that a constant may be.

    Update

    After clarification from the OP I came up with a new methods using -O0 -fverbose-asm -S and grep, code is as follows:

    #include 
    
    struct s {
            int i;
            char c;
            double d;
            char a[];
        };
    
    int main()
    {
        int offsetArray[4] = { offsetof(struct s, i ), offsetof( struct s, c ), offsetof(struct s, d ), offsetof(struct s, a )  } ;
    
        return 0 ;
    }
    

    build using:

    gcc -x c -std=c99 -O0 -fverbose-asm  -S main.cpp && cat main.s | grep offsetArray
    

    sample output (live example):

    movl    $0, -16(%rbp)   #, offsetArray
    movl    $4, -12(%rbp)   #, offsetArray
    movl    $8, -8(%rbp)    #, offsetArray
    movl    $16, -4(%rbp)   #, offsetArray
    

提交回复
热议问题