title: About compilation unit and Schwarz Counter and singleton pattern
body: <p>I look this example and practice it:
  <a href="https://novus.pixnet.net/blog/post/23784820" rel="nofollow noreferrer">https://novus.pixnet.net/blog/post/23784820</a></p>
  
  <p>(The code is at the end)</p>
  
  <p>The compile command is:</p>
  
  <pre><code>g++ sc.cc main.cc -o main.exe
  </code></pre>
  
  <p>I have 2 questions:</p>
  
  <ol>
  <li>The Compilation Unit has 2 unit which consist of sc and main. (correct?)</li>
  <li>I know this example (Schwarz Counter) is applied to iostream (C++).<strong>Singleton pattern</strong> looks suitable for this situation. Does <strong>Singleton pattern</strong> is better than <strong>Schwarz Counter</strong> in the case for unique and global (such as file io)?</li>
  </ol>
  
  <h2>Code:</h2>
  
  <p>sc.h</p>
  
  <pre class="lang-cpp prettyprint-override"><code>#include &lt;fstream&gt;
  
  class Log {
  friend class Initializer;
  public:
     void Print(const char* msg) {
        std::fputs(msg, onlyFile_);
     }
  
  private:
     static std::FILE* onlyFile_;
  };
  
  class Initializer {
  public:
     Initializer();
     ~Initializer();
  private:
     static int ref_;
  };
  
  extern Log log;
  static Initializer init;
  #endif
  </code></pre>
  
  <p>sc.cc</p>
  
  <pre><code>#include "s.h"
  
  std::FILE* Log::onlyFile_ = 0;
  int Initializer::ref_ = 0;
  
  Initializer::Initializer() {
     if (0 == ref_++) {
        Log::onlyFile_ = fopen("somefile.txt", "w");
     }
  }
  
  Initializer::~Initializer() {
     if (0 == --ref_) {
        fclose(Log::onlyFile_);
     }
  }
  </code></pre>
  
  <p>main.c</p>
  
  <pre class="lang-cpp prettyprint-override"><code>#include "s.h"
  int main(int argc, char const *argv[]) {
    log.Print("aa");
    return 0;
  }
  </code></pre>