how to assign multiple values into a struct at once?

前端 未结 6 1940
执笔经年
执笔经年 2020-12-02 13:15

I can do this on initialization for a struct Foo:

Foo foo =  {bunch, of, things, initialized};

but, I can\'t do this:

Foo f         


        
6条回答
  •  孤街浪徒
    2020-12-02 13:44

    Memory Footprint - Here is an interesting i386 addition.

    After much hassle, using optimization and memcpy seems to generate the smallest footprint using i386 with GCC and C99. I am using -O3 here. stdlib seems to have all sorts of fun compiler optimizations at hand, and this example makes use of that (memcpy is actually compiled out here).

    Do this by:

    Foo foo; //some global variable
    
    void setStructVal (void)   {
    
        const Foo FOO_ASSIGN_VAL = {    //this goes into .rodata
                .bunch       = 1,
                .of          = 2,
                .things      = 3,
                .initialized = 4
        };
    
        memcpy((void*) &FOO_ASSIGN_VAL, (void*) foo, sizeof(Foo));
    
        return;
    }
    

    Result:

    • (.rodata) FOO_ASSIGN_VAL is stored in .rodata
    • (.text) a sequence of *movl FOO_ASSIGN_VAL, %registers* occur
    • (.text) a sequence of movl %registers, foo occur

    Example:

    • Say Foo was a 48 field struct of uint8_t values. It is aligned in memory.

    • (IDEAL) On a 32-bit machine, this COULD be as quick as 12 MOVL instructions of immediates out to foo's address space. For me this is 12*10 == 120bytes of .text in size.

    • (ACTUAL) However, using the answer by AUTO will likely generate 48 MOVB instructions in .text. For me this is 48*7 == 336bytes of .text!!

    • (SMALLEST*) Use the memcpy version above. IF alignment is taken care of,

      • FOO_ASSIGN_VAL is placed in .rodata (48 bytes),
      • 12 MOVL into %register
      • 12 MOVL outof %registers are used in .text (24*10) == 240bytes.
      • For me then this is a total of 288 bytes.

    So, for me at least with my i386 code,

    - Ideal:    120 bytes
    - Direct:   336 bytes
    - Smallest: 288 bytes
    

    *Smallest here means 'smallest footprint I know of'. It also executes faster than the above methods (24 instructions vs 48). Of course, the IDEAL version is fastest & smallest, but I still can't figure that out.

    -Justin

    *Does anyone know how to get implementation of 'IDEAL' above? It is annoying the hell out of me!!

提交回复
热议问题