用于使用numpy扩展的C程序的Makefile

6 投票
2 回答
1072 浏览
提问于 2025-04-17 11:08

请问,怎样才能最简单、最优雅地找到numpy的包含路径,以便在目标系统上使用?然后再通过make命令来使用这些路径?目前我使用的是:

gcc ... -I/usr/include/python2.7/ -I/usr/lib/python2.7/site-packages/numpy/core/include/numpy/

我希望这两个路径能够根据构建所在的系统自动选择。

看起来我可以这样获取第二个路径:

python -c "import numpy; print numpy.__path__[0] + 'core/include/numpy/'"

但我对第一个路径不太确定,即使我知道了,也不太清楚如何在makefile中以简单优雅的方式使用它。

2 个回答

0

经过一些搜索和实验,我得出了以下结论:

CFLAGS = $(shell python-config --includes) $(shell python -c "import numpy; print '-I' + numpy.__path__[0] + '/core/include/numpy/'")

虽然不太确定这个方法有多可靠,但到目前为止在所有机器上都能正常工作。

我需要使用 $(shell ...) 来从命令行输出中设置 make 变量,因为 mux 提出的另一种方法对我来说不管用。

3

numpy.get_include() 是获取包含文件的最简单和最好的方法。如果你的 C 扩展模块使用了 numpy,那么在 Extension 中,你需要使用 include_dirs=[numpy.get_include()]。至于为什么 numpy.get_include() 似乎没有任何文档,我也不知道。

然后你可以按照用户 1056255 的建议去做,但可以稍微改进一下...

CFLAGS = $(shell python-config --includes) $(shell python -c "import numpy; print '-I' + numpy.get_include()")

撰写回答