title: Distutils: build multiple Python extension modules (written in Swig) that share a method
body: <p>I have four C++ files: A.h, A.cpp, B.h, B.cpp, and A.h is included in B.cpp</p>
  
  <p>A.h:</p>
  
  <pre><code>#pragma once 
  void A();
  </code></pre>
  
  <p>A.cpp:</p>
  
  <pre><code>#include &lt;iostream&gt;
  void A() {
      std::cout &lt;&lt; "A" &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>B.h:</p>
  
  <pre><code>#pragma once
  void B();
  </code></pre>
  
  <p>B.cpp:</p>
  
  <pre><code>#include "A.h"
  #include &lt;iostream&gt;
  void B() {
      A();
      std::cout &lt;&lt; "B" &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>Now I wrote two SWIG inerface files A.i and B.i</p>
  
  <p>A.i:</p>
  
  <pre><code>%module A
  %{
  #include "A.h"
  %}
  %include "A.h"
  </code></pre>
  
  <p>B.i:</p>
  
  <pre><code>%module B
  %{
  #include "B.h"
  %}
  %include "B.h"
  </code></pre>
  
  <p>The setup.py file is:</p>
  
  <pre><code>from distutils.core import setup, Extension
  A_ext = Extension( "_A", [ "A.i", "A.cpp", ], swig_opts = ['-c++'], extra_compile_args = ['-g'])
  B_ext = Extension( "_B", [ "B.i", "B.cpp", ], swig_opts = ['-c++'], extra_compile_args = ['-g'])
  setup(
      name = "test",
      version = "1.0",
      ext_modules = [ A_ext, B_ext ],
      py_modules = [ "A", "B" ]
  )
  </code></pre>
  
  <p>If I type the command below, it will show 'A'.</p>
  
  <pre><code>python -c 'import A; A.A()' 
  </code></pre>
  
  <p>If I type the command below, the segmentation fault appears:</p>
  
  <pre><code>python -c 'import B; B.B()'
  </code></pre>
  
  <p>How could I do to get this command run correctly? Since I don't want to compile B.cpp many times, is there any way except the one below?</p>
  
  <pre><code>B_ext = Extension( "_B", [ "B.i", "A.cpp", "B.cpp", ], swig_opts = ['-c++'], extra_compile_args = ['-g'])
  </code></pre>