Search code examples
pythonc++cython

How to override -DNDEBUG compile flag when building a Cython module


I have a Cython module that calls a C++ function via cdef extern. The C++ function has assert() statements, and I would like to check those assertions. However, when I create the module by calling python setup.py build_ext --inplace, GCC is always invoked with -DNDEBUG. Whenever the code is run, the assertions are not checked.

I can't find a way to override -DNDEBUG using setup.py. Is this possible?

Currently the only way I have found to deal with this is to manually call Cython, GCC, and g++ with the options that are used by python setup.py, but to take out -DNDEBUG. But there must be a simpler way.


Solution

  • You can manually undefine NDEBUG, if it is defined, prior to including <cassert>. Add the following lines to the top of the cpp file which contains these assert statements. Make sure these are the very first statements in that file.

    #ifdef NDEBUG
    # define NDEBUG_DISABLED
    # undef NDEBUG
    #endif
    #include <cassert>
    
    #ifdef NDEBUG_DISABLED
    # define NDEBUG        // re-enable NDEBUG if it was originally enabled
    #endif
    
    // rest of the file
    

    This will ensure that NDEBUG is not defined when the processor includes <cassert>, which will result in the assertion checks being compiled into your code.