This minimal example shows how to setup PyBind11 on Ubuntu 22.04. To learn more about PyBind11 check out the official documentation.
To try it out for yourself follow this guide.
Clone this repo, create a virtual Python environment, and install PyBind11 inside. Next, build the example.cpp
file. See commands below:
git clone <this_repo>
cd <this_repo>
python -m venv venv
source venv/bin/activate
pip3 install pybind11
clang++ -shared -fPIC -std=c++11 -I./pybind11/include/ `python3.10 -m pybind11 --includes` example.cpp -o mymodule.so `python3.10-config --ldflags`
Note: If you encounter any errors, check out the section Common Errors below.
You should now have a binary file called mymodule.so
in the root directory of your project. You can confirm that it got created by running:
ls
You can now further confirm that your c++ code can be executed from a python script by running:
ipython3
import mymodule
mymodule.add(5, 2)
Expected output is 7
as per the add()
function defined in example.cpp
.
Have fun with PyBind11!
For your own reference, see some common errors and possible fixes below.
Command 'clang++' not found, but can be installed with:
sudo apt install clang
Try install clang with:
sudo apt install clang
If during the compilation of example.cpp
you encounter the following error:
~/YourProject/venv/lib/python3.10/site-packages/pybind11/include/pybind11/detail/common.h:303:10: fatal error: 'cstddef' file not found
#include <cstddef>
^~~~~~~~~
1 error generated.
Run the following command first and then try again:
sudo apt install libstdc++-12-dev