# gcc options to remove space between arrays and other variables



## asp5 (Aug 19, 2012)

Hi all,


```
main() 
{
    int d[4];
    int b = 55;
    int c = 34;
    int e = 23;

    return 0;
}
```

For the above code I see that in some implementations of Gcc 

&d[4] = &b and 
other implementations &d[5] = &b.
As we can see the second implementation leaves some space between the arrays and other variables. b, c and e have no spaces between them in both the implementations. 

Is there a gcc option which tell it not to leave such spaces? 

Also, the second is on a powerpc (OS: OpenBSD) and the first is a x86 machine running FreeBSD. Both are 32 bit processors. 

Thanks.


----------



## kpa (Aug 19, 2012)

I would think that on the 2nd system (powerpc) the compiler tries to keep the stack boundary aligned at 4 times 32bits equaling 128bits. On i386 there may not be the same requirements. There seems to be an option that might be what you're looking for, this is an i386 and amd64 specific option:


```
-mpreferred-stack-boundary=num
       Attempt to keep the stack boundary aligned to a 2 raised to num
       byte boundary.  If -mpreferred-stack-boundary is not specified, the
       default is 4 (16 bytes or 128 bits).
```

But it seems to default to the same alignment as in the powerpc example :q

Which version of gcc(1) you used in the FreeBSD case? The manual page I quoted is from version 4.6.


----------



## asp5 (Aug 19, 2012)

kpa said:
			
		

> Which version of gcc(1) you used in the FreeBSD case? The manual page I quoted is from version 4.6.



Thanks, will look for similar options in PowerPC. I've FreeBSD 9.0 RELEASE and gcc version 4.2.1.

EDIT: I've seen that the stack-boundary option changes how the stack is setup, For eg:

```
0x0804843d <main+13>:   push   %ecx
0x0804843e <main+14>:   sub    $0x20,%esp   
0x08048441 <main+17>:   mov    $0x0,%eax
0x08048446 <main+22>:   add    $0x20,%esp
```

Though we need only 7 words of memory for the purpose of alignment, the compiler setup 8 words (0x20 bytes). This means that there is some space left after/before all the variables (array, b, c and e) ? But in the 2nd case (powerpc) the compiler decided to leave space between the array and the other variables, (in the x86 case the compiler leaves space before/after all the variables)? Is that how it works? I'm not familiar with the powerpc arch, so can not understand the assembly . Please let me know if the above interpretation is correct. If it is correct then how can I make the compiler leave space after/before the variables and not between the array and variables. 

Thanks.


----------



## Anonymous (Aug 19, 2012)

#pragma pack(n) where n may be 2, 4, 8, ... is what you are looking for.

For performance reasons, you might want to enclose only some structs with this directive. Anyway, the most portable option would be to use unions where possible.

Best regards

Rolf


----------

