【问题标题】:Python.h not found while building sample application with cmake and pybind11使用 cmake 和 pybind11 构建示例应用程序时找不到 Python.h
【发布时间】:2020-01-08 19:28:27
【问题描述】:

我想用 pybind11 构建简单的应用程序,pybind 已经用 cmake 安装在我的 Ubuntu 系统中(并进行安装)。我使用这个简单的 cmake 文件:

cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(trt_cpp_loader )
find_package(pybind11 REQUIRED)
add_executable(trt_cpp_loader main.cpp)
set_property(TARGET trt_cpp_loader PROPERTY CXX_STANDARD 11)

这是 main.cpp:

#include <iostream>
#include <pybind11/embed.h>
namespace py = pybind11;

using namespace std;
int main(){return 0;}

当我构建它时,我得到:

In file included from /usr/local/include/pybind11/pytypes.h:12:0,
                 from /usr/local/include/pybind11/cast.h:13,
                 from /usr/local/include/pybind11/attr.h:13,
                 from /usr/local/include/pybind11/pybind11.h:44,
                 from /usr/local/include/pybind11/embed.h:12,
                 from /home/stiv/lpr/trt_cpp_loader/main.cpp:2:
/usr/local/include/pybind11/detail/common.h:112:10: fatal error: Python.h: No such file or directory
 #include <Python.h>
          ^~~~~~~~~~
compilation terminated.

我该如何解决这个问题? (python-dev和python3-dev已经安装,Python.h可用)

【问题讨论】:

    标签: python c++ ubuntu cmake pybind11


    【解决方案1】:

    您需要使用pybind11_add_module 命令(请参阅https://pybind11.readthedocs.io/en/stable/compiling.html#building-with-cmake)来创建扩展模块的默认情况。

    如果目标确实是将 Python 嵌入到可执行文件中,则您有责任将 Python 头文件和库显式添加到 CMake 中的编译器/链接器命令中。 (请参阅https://pybind11.readthedocs.io/en/stable/compiling.html#embedding-the-python-interpreter 了解如何操作)

    【讨论】:

    • 能否具体说明第二种情况?
    • 请参阅参考页面,尤其是target_link_libraries(example PRIVATE pybind11::embed) 声明。
    【解决方案2】:

    按照Wenzel Jakobanswer,我想举一个CMakeLists.txt的例子来编译this tutorial中提供的例子:

    // example.cpp
    
    #include <pybind11/pybind11.h>
    
    int add(int i, int j) {
        return i + j;
    }
    
    PYBIND11_MODULE(example, m) {
        m.doc() = "pybind11 example plugin"; // optional module docstring
    
        m.def("add", &add, "A function which adds two numbers");
    }
    

    # example.py
    
    import example
    
    print(example.add(1, 2))
    

    # CMakeLists.txt
    
    cmake_minimum_required(VERSION 2.8.12)
    project(example)
    
    find_package(pybind11 REQUIRED)
    pybind11_add_module(example example.cpp)
    

    现在在根目录运行

    cmake .
    make
    

    现在运行 python 代码

    python3 example.py
    

    P.S. 我还写了一些指令here 用于编译/安装pybind11

    【讨论】:

    • @StepanYakovenko 我很高兴。实际上感谢您和 Wenzel 提供的答案。 :)
    【解决方案3】:

    也许只安装 Python 头文件?例如,在 Ubuntu 上,您可以安装 sudo apt-get install python-dev(或 python3-devpythonX.Y-dev)包。这可以解决这个问题。

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 1970-01-01
      • 2015-03-19
      • 2013-08-18
      • 1970-01-01
      • 2017-02-25
      • 2019-12-30
      • 1970-01-01
      • 2019-01-25
      相关资源
      最近更新 更多