ErectCrested
ErectCrested

Reputation: 68

GCC array opimization

I have a process with main() only and a lookup table that is mostly empty:

    int arr[10] = {0, 0, 0, 0, 1, 0, 0, 1, 0, 0};

When I put this array in global area outside of main() and compile with gcc -O2 file.c, I get the following executable:

    bash# size a.out
       text    data     bss     dec     hex filename
       1135     616       8    1759     6df a.out

When I put this array inside main() function and compile with gcc -O2 file.c, I get the following executable:

    bash# size a.out
       text    data     bss     dec     hex filename
       1135     560       8    1703     6a7 a.out

Then, I change the size of the array to 10000, without modifying the contents, and run the test again. This time the results are:

Outside main():

    bash# size a.out
       text    data     bss     dec     hex filename
       1135   40576       8   41719    a2f7 a.out

Inside main():

    bash# size a.out
       text    data     bss     dec     hex filename
       1135     560       8    1703     6a7 a.out

Why the optimization is not working when the array is in global area. Is there a way to keep a large mostly empty lookup table in global area and still have it optimized??

Upvotes: 2

Views: 388

Answers (1)

Petr Skocik
Petr Skocik

Reputation: 60067

/*have it start emtpy so it can go into .bss*/
int arr[10000];

//__attribute__((constructor))
void arr__init(void)
{
    //set the ones
    arr[4]=1; arr[7]=1; 
}

int main()
{
    //call the initializer
    //(or uncomment the constructor attr to have it called before main automatically (nonstandard))
    arr__init();
    return arr[4]+arr[7]+arr[2];
}

size call on the object file:

text       data     bss     dec     hex filename
148       0   40000   40148    9cd4 a.out

Upvotes: 1

Related Questions