首页 > 解决方案 > 如何强制库(pybind11)包含来自 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 而不是 Python2 的标头。

先感谢您!

PS:我使用的是 macOS 10.15.2

标签: pythonc++pybind11

解决方案


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

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

`python-config --includes`

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

二、有模块distutils:

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

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


推荐阅读