how to override -DNDEBUG compile flag when building cython module

柔情痞子 提交于 2019-12-23 09:04:03

问题


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.


回答1:


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.




回答2:


You can undefine NDEBUG in your setup.py file. Just use the undef_macros option when defining your extension:

extensions = [ Extension ( "myprog", [ mysrc.c ], undef_macros = [ "NDEBUG" ] ) ]

In the build output you'll see -DNDEBUG followed by -UNDEBUG, which overrides it. For more information on Extension options, see the distutils documentation.

Note, however, that an assert triggered in an extension module will cause the python, or ipython, interpreter to exit.



来源:https://stackoverflow.com/questions/24275714/how-to-override-dndebug-compile-flag-when-building-cython-module

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!