简体   繁体   中英

How to build and execute a cpp file with embedded python interpreter(pybind11)

I'm trying to find a way to build and run a cpp file with an embedded python interpreter using pybind11.

From this tutorial , it uses CMake but I'm looking for a way to do this without CMake.

Here's what I tried.

In example.cpp:

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

And in the Terminal when I run the following: (builds fine)

c++ -O3 -Wall -std=c++11 -undefined dynamic_lookup `python3 -m pybind11 --includes` example.cpp -o example

And then run the binary with

./example

I get the following error:

dyld: Symbol not found: _PyBaseObject_Type Referenced from: /Users/cuinjune/Desktop/pybindtest/./example Expected in: flat namespace in /Users/cuinjune/Desktop/pybindtest/./example zsh: abort ./example

Is there any possible way to properly build and execute a cpp file with an embedded python interpreter using pybind11? (without using CMake)

Link with the python library, which defines that symbol (and more that you will need).

Assuming a standard installation, that would be no more than adding:

`-lpython`

to the CLI (or -lpython3 etc. if multiple python libraries are present on your system). You could also add instead:

`python3-config --libs`

if your python3 has python3-config installed.

EDIT : based on the comments, the relevant library directory is not available to the linker in your setup. One option is to use the full set of flags instead:

`python3-config --ldflags`

where I'm still assuming that python3-config matches your python3 . If not, then the alternative is to get the directory distutils. Prepend with -L and add -lpython or -lpython3 depending on your installation:

-L`python3 -c 'import distutils.sysconfig as ds; print(ds.get_config_var("LIBDIR"))'` -lpython

(And yes, there is also an "LDFLAGS" config_var, but those are the flags for building python and are unlikely what you want.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM