title: Why is the address of static variables relative to the Instruction Pointer?
body: <p>I am following <a href="https://www.recurse.com/blog/7-understanding-c-by-learning-assembly" rel="noreferrer">this tutorial</a> about assembly.</p>
  
  <p>According to the tutorial (which I also tried locally, and got similar results), the following source code:</p>
  
  <blockquote>
  <pre><code>int natural_generator()
  {
          int a = 1;
          static int b = -1;
          b += 1;              /* (1, 2) */
          return a + b;
  }
  </code></pre>
  </blockquote>
  
  <p>Compiles to these assembly instructions:</p>
  
  <blockquote>
  <pre><code>$ gdb static
  (gdb) break natural_generator
  (gdb) run
  (gdb) disassemble
  Dump of assembler code for function natural_generator:
  push   %rbp
  mov    %rsp,%rbp
  movl   $0x1,-0x4(%rbp)
  mov    0x177(%rip),%eax        # (1)
  add    $0x1,%eax
  mov    %eax,0x16c(%rip)        # (2)
  mov    -0x4(%rbp),%eax
  add    0x163(%rip),%eax        # 0x100001018 &lt;natural_generator.b&gt;
  pop    %rbp
  retq   
  End of assembler dump.
  </code></pre>
  </blockquote>
  
  <p>(Line number comments <code>(1)</code>, <code>(2)</code> and <code>(1, 2)</code> added by me.)</p>
  
  <p><strong>Question</strong>: <strong>why</strong> is, in the compiled code, the address of the static variable <code>b</code> relative to the instruction pointer (RIP), which constantly changes (see lines <code>(1)</code> and <code>(2)</code>), and thus generates more complicated assembly code, rather than being relative to the specific section of the executable, where such variables are stored?</p>
  
  <p>According to the mentioned tutorial, there <strong>is</strong> such a section:</p>
  
  <blockquote>
    <p>This is because the value for <code>b</code> is hardcoded in a <strong>different section</strong> of
    the sample executable, and it’s loaded into memory along with all the
    machine code by the operating system’s loader when the process is
    launched.</p>
  </blockquote>
  
  <p>(Emphasis mine.)</p>