我正在尝试按照本教程编译一个简单的python / C示例:
https://www.swig.org/tutorial.html
我在MacOS上使用Anaconda python。
但是,当我跑
gcc -c example.c example_wrap.c -I/Users/myuser/anaconda/include/
我明白了:
example_wrap.c:130:11: fatal error: 'Python.h' file not found # include ^
似乎在一些问题中报告了这个问题:
尝试编译C扩展模块时缺少Python.h.
缺少Python.h,无法找到
Python.h:没有这样的文件或目录
但似乎没有人提供特定于MacOS上的Anaconda的答案
有谁解决了这个?
在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_wrap.c
,而是包含example.i
,并且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
,您可以使用single命令构建扩展模块
$ 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
以上就是c/c++开发分享使用swig和Anaconda Python找不到Python.h相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/545041.html