title: Making C module variables accessible as read-only
body: <p>I would like to give a module variable a read-only access for client modules.
  Several solutions:</p>
  
  <p><strong>1</strong>. The most common one:</p>
  
  <pre><code>// module_a.c
  static int a;
  
  int get_a(void)
  {
      return a;
  }
  
  // module_a.h
  int get_a(void);
  </code></pre>
  
  <p>This makes one function per variable to share, one function call (I am thinking both execution time and readability), and one copy for every read. Assuming no optimizing linker.</p>
  
  <p><strong>2</strong>. Another solution:</p>
  
  <pre><code>// module_a.c
  static int _a;
  const int * const a = &amp;_a;
  
  // module_a.h
  extern const int * const a;
  
  // client_module.c
  int read_variable = *a;
  *a = 5;  // error: variable is read-only
  </code></pre>
  
  <p>I like that, besides the fact that the client needs to read the content of a pointer. Also, every read-only variable needs its <code>extern const</code> pointer to <code>const</code>.</p>
  
  <p><strong>3</strong>. A third solution, inspired by the second one, is to hide the variables behind a struct and an extern pointer to struct. The notation <code>module_name-&gt;a</code> is more readable in the client module, in my opinion.</p>
  
  <p><strong>4</strong>. I could create an <em>inline definition</em> for the <code>get_a(void)</code> function. It would still look like a function call in the client module, but the optimization should take place.</p>
  
  <p>My questions:</p>
  
  <ul>
  <li><p>Is there a best way to make variables modified in a module accessible as read-only in other modules? Best in what aspect?</p></li>
  <li><p>Which solutions above would you accept or refuse to use, and why?</p></li>
  </ul>
  
  <p>I am aware that this is microoptimization - I might not implement it - but I am still interested in the possibility, and above all in the knowing.</p>