Very simple CMakeLists to build a basic python module. CMake is a build-generator;
It reads a description of your project and then uses this to generate the actual
build system - usually Makefiles, but can also generate e.g. IDE projects. This is
why you actually use make
to do the build.
Add the CMakeLists.txt to the path with your source, or check out this gist e.g.
$ ls
CMakeLists.txt README.md hello_ext.cpp
Then make a build directory (cmake encourages out-of-source build directories), go into it and run cmake:
$ mkdir _build
$ cd _build
$ cmake ..
...
-- Found PythonLibs: /usr/lib/libpython2.7.dylib (found suitable version "2.7.10", minimum required is "2.7")
-- Boost version: 1.65.0
-- Found the following Boost libraries:
-- python
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/nickd/tmp/bp/_bui
You can then build the library with make
:
$ make
Scanning dependencies of target hello_ext
[ 50%] Building CXX object CMakeFiles/hello_ext.dir/hello_ext.cpp.o
[100%] Linking CXX shared module hello_ext.so
[100%] Built target hello_ext
And this should be importable:
$ python
>>> from hello_ext import greet
>>> greet()
'hello, world'
Amending/doing different builds/targets should be relatively intuitive from the CMakeLists.txt.
Implementation Note: Misses out a couple of Cmake best-practices (at time of writing in the middle of a boost/cmake version shear that causes issues with something called 'Imported Targets').
I followed the example and it builds as expected, but when I then go to the dir where the library file was installed and do
python
and
from hello_ext import greet
I get
Traceback (most recent call last):
File "", line 1, in
ModuleNotFoundError: No module named 'hello_ext'