Below is a CMakeLists.txt which is used for building the source code “sampling.cpp”, during which pybind11 helps to output a shared library “sampling.so” that can be imported by python.
cmake_minimum_required(VERSION 2.8.12)
project(sampling)
set(CMAKE_CXX_STANDARD 11)
set(pybind11_DIR /home/something/miniconda3/envs/TestEnv/lib/python3.6/site-packages/pybind11/share/cmake/pybind11/)
find_package(pybind11 REQUIRED) # add_subdirectory(pybind11)
pybind11_add_module(sampling sampling.cpp)
# add 2021/6/29
# For building with cmake, to make 'find_package' work, there are several ways:
# 1. In the virtual env, use: pip install "pybind11[global]", instead of: pip install pybind11, then there is no need to set pybind11_DIR;
# 2. Or, add the 5th line code to set pybind11_DIR which includes the configuration file "pybind11Config.cmake" (or "pybind11-config.cmake");
# 3. Add the installation prefix of "pybind11" to CMAKE_PREFIX_PATH --- how ? -> by replacing [cmake .. ] with [cmake -DCMAKE_PREFIX_PATH=/home/xiongkai/miniconda3/envs/s2cnn/lib/python3.6/site-packages/pybind11/ .. ]
# 4. By providing "Findpybind11.cmake" in CMAKE_MODULE_PATH --- how ?
# Or, building manually:
# c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) sampling.cpp -o sampling$(python3-config --extension-suffix)
# Interesting, the output .so by above two building methods have different size.
# Specifically, 144 kb for building manually, and 587 kb for cmake building.
# one more note
# pybind11_add_module() is identical to:
# add_library(sampling MODULE sampling.cc) # if no MODULE, then outputs a static '.a' library
# target_link_libraries(sampling PRIVATE pybind11::module) # the output '.so' file is of size 798 kb. It is not a high quality generation.