Reputation: 1395
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
Reputation: 58442
It's pretty straightforward. You need to make the following changes:
-I
flags).-I
flags).-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