我从pybind11
开始,试图编译第一个示例。我用Xubuntu 20.04。我的系统python是3.8,但是我只为python 3.10安装了pybind11
,这是当我在命令提示符下输入python
时执行的版本。当我运行pybind11
文档中给出的编译命令时:
c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3.10 -m pybind11 --includes) example.cpp -o example$(python3.10-config --extension-suffix)
我得到错误信息:
fatal error: Python.h: No such file or directory
213 | #include <Python.h>
我按照Python.h: No such file or directory给出的可接受的致命错误答案中的建议运行
sudo apt install python3.10-dev
,但这没有影响,即使Python.h
现在存在于/usr/include/python3.10
中。我应该说明一下,此时我并没有使用虚拟环境。
编辑
python3.10-config --cflags
-I/usr/include/python3.10 -I/usr/include/python3.10 -Wno-unused-result -Wsign-compare -g -fstack-protector-strong -Wformat -Werror=format-security -DNDEBUG -g -fwrapv -O2 -Wall
编辑
我按照9769953的建议修改了命令:
Pybind11Test$ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3.10 -m pybind11 python3.10-config --includes) example.cpp -o example$(python3.10-config --extension-suffix)
usage: __main__.py [-h] [--includes] [--cmakedir]
__main__.py: error: unrecognized arguments: python3.10-config
example.cpp:1:10: fatal error: pybind11/pybind11.h: No such file or directory
1 | #include <pybind11/pybind11.h>
| ^~~~~~~~~~~~~~~~~~~~~
compilation terminated.
添加python3.10-config
给了我一个unrecognized argumnents
错误,但编译在不同的地方失败。#include <pybind11/pybind11.h>
是example.cpp
的第一行。
文件存在于
/home/saul/.local/lib/python3.10/site-packages/pybind11/include/pybind11/pybind11.h
编辑
最新尝试
Pybind11Test$ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3.10 -m pybind11 --includes) example.cpp -o example.out
In file included from /home/saul/.local/lib/python3.10/site-packages/pybind11/include/pybind11/detail/../cast.h:13,
from /home/saul/.local/lib/python3.10/site-packages/pybind11/include/pybind11/detail/../attr.h:13,
from /home/saul/.local/lib/python3.10/site-packages/pybind11/include/pybind11/detail/class.h:12,
from /home/saul/.local/lib/python3.10/site-packages/pybind11/include/pybind11/pybind11.h:13,
from example.cpp:1:
/home/saul/.local/lib/python3.10/site-packages/pybind11/include/pybind11/detail/../detail/common.h:213:10: fatal error: Python.h: No such file or directory
213 | #include <Python.h>
| ^~~~~~~~~~
compilation terminated.
问题是操作系统将Python 3.10的头文件安装在/usr/include/python3.10/include
中。这使它们与默认的系统Python(3.8)分开,以防也安装了开发包(否则,一组文件将覆盖另一组文件)。
但是/usr/include/python3.10/include
不在c++编译器包含的默认搜索路径中;你必须把它加起来。您可以手动执行此操作,但python-config
工具通常会(更好地)处理此操作。添加
python3.10-config --includes
作为子shell命令($(...)
)到命令行。与pybind类似,使用$(python -m pybind --includes)
让编译器查找pybind的包含文件。
显然,需要使用正确的python-config
变体,因此python3.10-config
。
共享库文件较少,并且通过文件名中包含Python版本来命名,因此这些文件都可以安全地放在/usr/lib/x86_64-linux-gnu/
中。您将在该目录中发现libpython3.8.so
和libpython3.10.so
相邻。因此不需要添加库搜索路径(python-config
甚至不存在该选项,但它包含在python3.10-config --ldflags
中)。
总而言之,命令看起来像:
c++ -O3 -Wall -shared -std=c++11 -fPIC
$(python3.10-config --includes)
$(python3.10 -m pybind11 --includes)
-o example$(python3.10-config --extension-suffix)
example.cpp
(为了便于阅读,分隔几行)