使用cmake和pybind11构建示例应用程序时未找到Python.h

发布于 2021-01-29 14:09:53

我想用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可用)

关注者
0
被浏览
934
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    遵循Wenzel Jakob回答,我想举一个例子,CMakeLists.txt用于编译本教程中提供的示例:

    // 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
    

    PS
    我还写了一些说明用于编译/安装pybind11



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看