3

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?

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't seem to really answer the question.
@ZackLee, I believe it answers the question - the OP said they need to extend a pre-existing makefile, so I described the changes that they'd need to make to their makefile. If you're writing a makefile from scratch, you could use one of the various examples or templates online, then apply the changes described here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.