A simple boilerplate for starting a C++ project built with CMake with PyBind11 bindings. In this example, a library for calcluations called calc
is built then wrapped with Python bindings.
CMake
is aMakefile
wrapper. That is, it generates Makefiles.- A C++ project with CMake should have the following structure (also available at GitLab).
- The current project is an example of it.
- Bundling C++ libraries with a Python package is trivial if we have access to the static version of the libraries. We need only to create a shared library which includes the static versions of the dependencies and may be deployed without needing to install anything.
- However, if we only have access to the shared version of the libraries, the issue is more complex. As of now, I know about a few ways of circumventing this:
- Using
auditwheel
to build a Wheel that includes the shared libraries by copying them and modifying therpath
. - Manually doing what
auditwheel
does, using commands such asldd
to find the dependencies of an executable. - Instead of using
rpath
, usingLD_LIBRARY_PATH
(difference betweenrpath
andLD_LIBRARY_PATH
). - The easiest one is simply providing a script for installing the dependencies, however this implies more work for the final user.
- Using
To add pybind11 as a submodule to the current directory, add it as a submodule. You should choose the stable
branch of pybind11:
git submodule add https://github.com/pybind/pybind11 ./pybind11 -b stable
git submodule update --init
mkdir build && \
cd build && \
cmake .. && \
cmake --build .
- The
cmake ..
command creates the necessary files and Makefiles from theCMakeLists.txt
configuration in the parent directory. cmake --build .
runs the makefiles to build the binary files.
To generate the documentation you'll need to install Doxygen, which in turn requires Flex and Bison.
sudo apt-get install flex
sudo apt-get install bison
Then to actually build the docs (requires Doxygen, output in build/docs/html):
cd build
cmake --build . --target docs
The Dockerfile
is already built to automatically install the generated Python modules using pip
. To verify the bindings working, run:
python
Then:
import bindings
help(bindings)
bindings.add(1, 2) # should output 3
bindings.display() # should output 0, meaning OpenCV functions work (only if OpenCV library is installed or otherwise included in the Wheel)
- Author: José Aleixo Cruz