Python.h not found using swig and Anaconda Python

后端 未结 1 1509
执笔经年
执笔经年 2021-01-04 13:52

I\'m trying to compile a simple python/C example following this tutorial:

http://www.swig.org/tutorial.html

I\'m on MacOS using Anaconda python.

howe

相关标签:
1条回答
  • 2021-01-04 14:37

    Use the option -I/Users/myuser/anaconda/include/python2.7 in the gcc command. (That's assuming you are using python 2.7. Change the name to match the version of python that you are using.) You can use the command python-config --cflags to get the full set of recommended compilation flags:

    $ python-config --cflags
    -I/Users/myuser/anaconda/include/python2.7 -I/Users/myuser/anaconda/include/python2.7 -fno-strict-aliasing -I/Users/myuser/anaconda/include -arch x86_64 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
    

    However, to build the extension module, I recommend using a simple setup script, such as the following setup.py, and let distutils figure out all the compiling and linking options for you.

    # setup.py
    
    from distutils.core import setup, Extension
    
    
    example_module = Extension('_example', sources=['example_wrap.c', 'example.c'])
    
    setup(name='example', ext_modules=[example_module], py_modules=["example"])
    

    Then you can run:

    $ swig -python example.i
    $ python setup.py build_ext --inplace
    

    (Take a look at the compiler commands that are echoed to the terminal when setup.py is run.)

    distutils knows about SWIG, so instead of including example_wrap.c in the list of source files, you can include example.i, and swig will be run automatically by the setup script:

    # setup.py
    
    from distutils.core import setup, Extension
    
    
    example_module = Extension('_example', sources=['example.c', 'example.i'])
    
    setup(name='example', ext_modules=[example_module], py_modules=["example"])
    

    With the above version of setup.py, you can build the extension module with the single command

    $ python setup.py build_ext --inplace
    

    Once you've built the extension module, you should be able to use it in python:

    >>> import example
    >>> example.fact(5)
    120
    

    If you'd rather not use the script setup.py, here's a set of commands that worked for me:

    $ swig -python example.i
    $ gcc -c -I/Users/myuser/anaconda/include/python2.7 example.c example_wrap.c 
    $ gcc -bundle -undefined dynamic_lookup -L/Users/myuser/anaconda/lib example.o example_wrap.o -o _example.so
    

    Note: I'm using Mac OS X 10.9.4:

    $ gcc --version
    Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
    Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
    Target: x86_64-apple-darwin13.3.0
    Thread model: posix
    
    0 讨论(0)
提交回复
热议问题