title: Definition and declaration of global variables using preprocessor trick
body: <p>I am currently looking through the code written by senior engineer. The code works fine but  i am trying to figure out one detail.</p>
  
  <p>He uses quite a few global variables and his code is broken down into a lot of separate files. So he uses a technique to make sure that global vars are declared everywhere where he needs to access them but are only defined once.</p>
  
  <p>The technique is new to me but I read few articles on the internet and got some understanding about how it works. He uses </p>
  
  <blockquote>
    <p>#undef EXTERN<br/></p>
  </blockquote>
  
  <p>followed by conditional definition of EXTERN as an empty string or actual extern. There is a very good article <a href="http://www.mathcs.emory.edu/~cheung/Courses/255/Syllabus/1-C-intro/cprep2.html" rel="nofollow noreferrer"><strong>here</strong></a> explaining how it works. Also there is a discussion <a href="https://stackoverflow.com/questions/2216765/variable-definition-in-header-files"><strong>here</strong></a></p>
  
  <p>What gets me confused is that all examples I saw on the web suggest to include header file in a regular way in all of the source files that need it except for one. In this single special case line that includes header is preceded by definition of a symbol that will ensure that EXTERN will be defined to an empty string and .. so on (see link above). Typically this single special case is in main or in a separate source file dedicated to the declaration of global variables.</p>
  
  <p>However in the code that I am looking at this special case is <strong>always</strong> in the source file that corresponds the header. Here is the minimal example:</p>
  
  <p>"<strong>peripheral1.h</strong>" :</p>
  
  <pre><code>#undef EXTERN
  #ifndef PERIPHERAL_1_CPP
  #define EXTERN extern
  #else
  #define EXTERN
  #endif
  
  EXTERN void function1(void);
  </code></pre>
  
  <p>"<strong>peripheral1.cpp</strong>" :</p>
  
  <pre><code>#define PERIPHERAL_1_CPP
  #include "peripheral1.h"
  
  function1()
  {
      //function code code here
  }
  </code></pre>
  
  <p>Everywhere else in the code he just does</p>
  
  <pre><code>#include "peripheral1.h"
  </code></pre>
  
  <p>My question is <strong>how</strong> and <strong>why</strong> does that work? In other words, how does compiler know where to define and where to just declare function (or variable, or class ...)? And why is it ok in above example to have the lines :</p>
  
  <pre><code>#define PERIPHERAL_1_CPP
  #include "peripheral1.h"
  </code></pre>
  
  <p>in actual peripheral1.cpp rather then in main.cpp or elsewhere?</p>
  
  <p>Or am I missing something obvious here?</p>