Derk
Derk

Reputation: 1395

How to embedding Python in C++ with PyBind and make instead of CMake?

I am trying to embed some Python code in C++ with PyBind. Most of documentation is on extending Python with C++, but I am interested in embedding:

On http://pybind11.readthedocs.io/en/stable/advanced/embedding.html there is a simple example with cmake. However for my project I have to extend a makefile.

Is it possible to change this example

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)

with this c++ file

#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
}

to a version with a makefile?

Upvotes: 3

Views: 3272

Answers (1)

Josh Kelley
Josh Kelley

Reputation: 58442

It's pretty straightforward. You need to make the following changes:

  1. Add the pybind11 include directory to your includes (-I flags).
  2. Add the Python 3 headers to your includes (-I flags).
  3. Add the Python 3 libraries to your libraries (-L flags).

Python's python3-config program is the best way of doing #2 and #3.

For example, if you have a makefile that looks something like this:

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

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

Then you'll need to change it like this:

%.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)

In practice, your Makefile probably has variables giving the include paths, C++ compiler flags, libraries, and/or linker flags, so you'd add the -I and python3-config calls there.

Upvotes: 2

Related Questions