How to build a Cython extension using CMake

Skip to first unread message

Corbin Foucart

Apr 21, 2022, 12:14:57 AMApr 21
to cython-users
Hello everyone,

I'm new to Cython, and I have the following problem:
  • I have a very complicated C++ library with lots of dependencies which I would like to wrap with Cython
  • I build the library, including the shared object file I'd like to wrap, using CMake
  • I need all the CMake information in order to compile the Cython code, but don't know how to incorporate it
For example, if I declare a simple class, similar to the tutorial (but try to #include something from my complicated library):

#ifndef BINDING_H
#define BINDING_H

namespace TestClass

class Rectangle


    void talk();
    int x;


#include <iostream>
#include "binding.h"

// this file is discoverable when building the so with cmake
#include <my_complicated_library/include/header.h>

namespace TestClass

  : x(16)

Rectangle::~Rectangle() {}

void Rectangle::talk()
  std::cout << "test class printed, x:" << x << std::endl;

and the usual rect.pyx and rect.pyd wrapping the two C++ files, I can compile the shared object file in CMakeLists.txt


// complicated build procedure

// binding library

Running cmake is able to build the shared object file fine, but running

from setuptools import setup
from Cython.Build import cythonize


fails, as it has no idea how to resolve the #include <my_complicated_libary/head.h> statement; I get the expected "fatal error: my_complicated_library/header.h: no such file or directory'. If I remove this line, everything works fine, but I can't use the definitions in my C++ library. This particular header has many other dependencies managed by CMake, so I don't think it's a matter of adding an include directory.

It seems the best way would be doing the Cython compilation in CMake directly, but I don't know how to do that. I can't be the only one attempting to wrap a library built by CMake.

Any guidance would be greatly appreciated!


Reply all
Reply to author
0 new messages