如何强制库(pybind11)包含 Python3 中的 <Python.h>?

How to force a library(pybind11) to include <Python.h> from Python3?

我正在使用 pybind11 库为我的 C++ 代码创建 Python 绑定。

当我编译包含 <pybind11/pybind11.h> 的绑定代码文件时,它会生成以下错误:

/usr/local/include/pybind11/detail/common.h:112:10: fatal error: 'Python.h' file
      not found
#include <Python.h>

我可以通过将其更改为 #include <Python/Python.h> 来修复此错误,但该库使用 Python 2.7 生成绑定。

所以我尝试将其更改为 #include "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/include/python3.7m/Python.h",现在库使用 Python 3.7 生成绑定,这正是我想要的。

尽管此方法有效,但我想知道是否有更简洁的方法让库始终包含 Python3 中的 headers 而不是 Python2。

提前致谢!

P.S: 我使用的是 macOS 10.15.2

有几种方法,但 AFAIK,none 在所有平台上都是一致的(这就是为什么像 cmake(参见:https://github.com/pybind/cmake_example)这样的东西通常是首选)。

首先是python-config,即加:

`python-config --includes`

(带反引号)到 CLI。我的问题是,它是通过 $PATH 找到的(因此,如果该安装没有 python-config,则不需要匹配您 运行ning 的 python 版本) 并且根据分布,python2python3 可能分别有 python-configpython3-config

其次,有模块distutils:

`python3 -c 'import distutils.sysconfig as ds; print(ds.get_python_inc())'`

它的优点是 运行 来自您选择的实际 python。一般来说,distutils 也不是跨平台完全一致的,但 get_python_inc 是一个安全的选择。