title: Order of variables in specific sections when enabling optimization in gcc
body: <p>Here is an extremely simple test case:</p>
  
  <pre><code>int a __attribute__ ((section("section")));
  int b __attribute__ ((section("section")));
  int c __attribute__ ((section("section")));
  </code></pre>
  
  <p>If I compile this file with GCC 8, with no optimizations and dump the object file I get the variables in the exact order as in the source file:</p>
  
  <pre><code>$ gcc -c order.c
  $ nm -n order.o
  0000000000000000 D a
  0000000000000004 D b
  0000000000000008 D c
  </code></pre>
  
  <p>However if I enable the optimization (any level), the variables are reversed in memory:</p>
  
  <pre><code>$ gcc -O -c order.c
  $ nm -n order.o
  0000000000000000 D c
  0000000000000004 D b
  0000000000000008 D a
  </code></pre>
  
  <p>As I need to keep consistent addresses of various variables in specific memory section for different versions of the program, I decided to put all of these variables in the same source file. This is for an embedded project and the section of memory I'm using has backup battery power, so its contents are not lost when the device is powered down. However I also need the addresses of "old" objects to remain constant and I don't want them to change when I add some "new" objects.</p>
  
  <p>So I'm wondering whether this particular behavior of GCC is something which I could control with any compiler flag (other than disabling optimizations [; ) and whether this is something consistent across different versions of GCC? For example can I assume that in GCC 11, in year 2022, the order of the variables in the memory will still be reverse of the order in source file, or maybe someday the order will be different than today with GCC 8?</p>