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

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

本文关键字:lt Python gt Python3 何强制 pybind11 包含      更新时间:2023-10-16

我正在使用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 而不是 Python2 的标头。

提前谢谢你!

PS:我使用的是macOS 10.15.2

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

首先,有python-config,即添加:

`python-config --includes`

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

其次,有模块特性:

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

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