title: embed python in matlab mex file on os x
body: <p>I'm trying to embed Python into a MATLAB mex function on OS X. I've seen references that this can be done (eg <a href="http://www.daniweb.com/forums/thread171969.html#" rel="nofollow noreferrer">here</a>) but I can't find any OS X specific information. So far I can successfully build an embedded Python (so my linker flags must be OK) and I can also build example mex files without any trouble and with the default options:</p>
  
  <pre><code>jm-g26b101:mex robince$ cat pytestnomex.c
  #include &lt;Python/Python.h&gt;
  
  int main() {
    Py_Initialize();
    PyRun_SimpleString("print 'hello'"); 
    Py_Finalize();
    return 0;
  }
  jm-g26b101:mex robince$ gcc -arch i386 pytestnomex.c -I/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -L/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/config -ldl -lpython2.5
  jm-g26b101:mex robince$ ./a.out
  hello
  </code></pre>
  
  <p>But when I try to build a mex file that embeds Python I run into a problem with undefined symbol main. Here is my mex function:</p>
  
  <pre><code>#include &lt;Python.h&gt;
  #include &lt;mex.h&gt;
  
  void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[])
  {
      mexPrintf("hello1\n");
      Py_Initialize();
      PyRun_SimpleString("print 'hello from python'");
      Py_Finalize();
  }
  </code></pre>
  
  <p>Here are the mex compilation steps:</p>
  
  <pre><code>jm-g26b101:mex robince$ gcc -c  -I/Applications/MATLAB_R2009a.app/extern/include -I/Applications/MATLAB_R2009a.app/simulink/include -DMATLAB_MEX_FILE  -arch i386 -I/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5  -DMX_COMPAT_32 -O2 -DNDEBUG  "pytest.c"
  jm-g26b101:mex robince$ gcc -O  -arch i386 -L/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/config -ldl -lpython2.5 -o  "pytest.mexmaci"  pytest.o  -L/Applications/MATLAB_R2009a.app/bin/maci -lmx -lmex -lmat -lstdc++
  Undefined symbols:
    "_main", referenced from:
        start in crt1.10.6.o
  ld: symbol(s) not found
  collect2: ld returned 1 exit status
  </code></pre>
  
  <p>I've tried playing around with arch settings (I added -arch i386 it to try and keep everything 32bit - I am using the python.org 32 bit 2.5 build), and the order of the linker flags, but haven't been able to get anywhere. Can't find much online either. Does anyone have any ideas of how I can get this to build?</p>
  
  <p>[EDIT: should probably add I'm on OS X 10.6.1 with MATLAB 7.8 (r2009a), Python 2.5.4 (python.org) - I've tried both gcc-4.0 and gcc-4.2 (apple)]</p>