c++ - 如何使用 PyBind 将 Python 嵌入到 C++ 中,而不是使用 CMake?

标签 c++ makefile g++ pybind11

我正在尝试使用 PyBind 在 C++ 中嵌入一些 Python 代码。大多数文档都是关于使用 C++ 扩展 Python,但我对嵌入感兴趣:

关于 http://pybind11.readthedocs.io/en/stable/advanced/embedding.html cmake 有一个简单的例子。但是对于我的项目,我必须扩展一个 makefile。

是否可以更改此示例

cmake_minimum_required(VERSION 3.0)
project(example)

find_package(pybind11 REQUIRED)  # or `add_subdirectory(pybind11)`

add_executable(example main.cpp)
target_link_libraries(example PRIVATE pybind11::embed)

用这个c++文件

#include <pybind11/embed.h> // everything needed for embedding
namespace py = pybind11;

int main() {
    py::scoped_interpreter guard{}; // start the interpreter and keep it alive

    py::print("Hello, World!"); // use the Python API
}

到带有 makefile 的版本?

最佳答案

这很简单。您需要进行以下更改:

  1. 将 pybind11 包含目录添加到您的包含(-I 标志)。
  2. 将 Python 3 header 添加到您的包含(-I 标志)。
  3. 将 Python 3 库添加到您的库中(-L 标志)。

Python 的 python3-config 程序是执行#2 和#3 的最佳方式。

例如,如果您有一个看起来像这样的 makefile:

%.o: %.cc
    $(CXX) -o $@ -c $^

main: main.o
    $(CXX) -o $@ $^

然后你需要像这样改变它:

%.o: %.cc
    $(CXX) -o $@ -c $^ -Ipath/to/pybind11-2.2.3/include $(shell python3-config --includes)

main: main.o
    $(CXX) -o $@ $^ $(shell python3-config --libs)

在实践中,您的 Makefile 可能包含提供包含路径、C++ 编译器标志、库和/或链接器标志的变量,因此您需要添加 -Ipython3-config 在那里调用。

关于c++ - 如何使用 PyBind 将 Python 嵌入到 C++ 中,而不是使用 CMake?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47678976/

相关文章:

c++ - 如何更新到 mingw-gcc 4.8.2?

c++ - 重载==函数没有被调用

makefile - 删除 Makefile 中配方失败的目标

gcc - 使用Makefile交叉编译内核。如何抑制“Wunused-but-set-variable”警告

c++ - 为什么 clang 要求在模板中调用函数之前先声明该函数?

c++ - 获取程序中的当前优化级别

c++ - 警告 LNK4075 : ignoring '/EDITANDCONTINUE' due to '/INCREMENTAL:NO' specification

c++ - 使用 C++ 和文件查找曲线下的面积

makefile - 检查 Makefile 中的标志

c++ - lambda 可以作为 C++17 中的模板参数传递吗?