title: In C++, why must class member functions be defined outside class for separate compilation?
body: <p>The following is a simple example for separate compilation:</p>
  <pre class="lang-cpp prettyprint-override"><code>// mod.cpp
  #include &lt;cstdio&gt;
  
  class MyModule {
  public:
      void print_msg();
  };
  
  void MyModule::print_msg() {
      printf(&quot;hello from module\n&quot;);
  }
  </code></pre>
  <pre class="lang-cpp prettyprint-override"><code>// main.cpp
  class MyModule {
  public:
      void print_msg();
  };
  
  int main() {
      MyModule a;
      a.print_msg();
  }
  </code></pre>
  <p>We can compile and run it with</p>
  <pre class="lang-bash prettyprint-override"><code>g++ main.cpp -c -o main.o
  g++ mod.cpp -c -o mod.o
  g++ main.o mod.o -o main
  ./main
  </code></pre>
  <p>The above works fine, but if I move the definition of <code>MyModule::print_msg</code> inside the class:</p>
  <pre class="lang-cpp prettyprint-override"><code>// mod.cpp
  #include &lt;cstdio&gt;
  
  class MyModule {
  public:
      void print_msg() { printf(&quot;hello from module\n&quot;); }
  };
  </code></pre>
  <p>I get an 'undefined reference' error for compiling <code>main</code>:</p>
  <pre class="lang-bash prettyprint-override"><code>g++ main.cpp -c -o main.o  # OK
  g++ mod.cpp -c -o mod.o    # OK
  g++ main.o mod.o -o main   # undefined reference error
  /usr/bin/ld: main.o: in function `main':
  main.cpp:(.text+0x23): undefined reference to `MyModule::print_msg()'
  collect2: error: ld returned 1 exit status
  </code></pre>
  <p>I know that the former is the standard way and the class definition should go to a header file, but I wonder why the second method doesn't work.</p>