在gcc 命令中使用选项-I/Users/myuser/anaconda/include/python2.7。 (假设您使用的是 python 2.7。更改名称以匹配您正在使用的 python 版本。)您可以使用命令python-config --cflags 获取完整的推荐编译标志集:
$ 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
但是,要构建扩展模块,我建议使用简单的设置脚本,例如以下setup.py,并让distutils 为您找出所有编译和链接选项。
# 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"])
然后就可以运行了:
$ swig -python example.i
$ python setup.py build_ext --inplace
(查看运行setup.py 时回显到终端的编译器命令。)
distutils 了解 SWIG,因此您可以将example.i 包括在源文件列表中,而不是在源文件列表中包括example_wrap.c,并且swig 将由安装脚本自动运行:
# 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"])
使用以上版本的setup.py,您可以使用单个命令构建扩展模块
$ python setup.py build_ext --inplace
一旦你构建了扩展模块,你应该就可以在 python 中使用它了:
>>> import example
>>> example.fact(5)
120
如果您不想使用脚本 setup.py,这里有一组对我有用的命令:
$ 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
注意:我使用的是 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