I'm writing a library with many asserts. The library is much slower with asserts turned on and the whole point of the library is that it is fast, so the asserts only make sense when testing or diagnosing a bug. I'm using autoconf and it seems to be standard practice to require the user to know about this issue and pass a flag to configure to disable asserts. In that case only an expert user will know enough to install an appropriate version of the library! Is that really what I should do, and if so, are there good reasons for that beyond just "that's what expert users and other programmers will expect?"
Edit: Here's an example of a discussion stating that you should not define NDEBUG by default in release mode, though with no other reason given that it is surprising to do that.
I think I've figured this out now. The problem with defining NDEBUG is that it can lead to undefined behavior. Mine is a template library with some non-template parts, so my code gets inlined into other people's binaries. If I define NDEBUG when compiling the non-inline code, and then the client code gets compiled without NDEBUG, then there will be two incompatible versions of the code from the headers - one with asserts and one without. This leads to undefined behavior and I have encountered this issue as a mysterious crash once before myself. So I do not think that a library should define NDEBUG - the person or build system in charge of compiling everything on a given computer should be the one to decide about NDEBUG.
However, I do not have to define NDEBUG just to make my library run without asserts by default. I now have a macro MYLIB_DEBUG and MYLIB_ASSERT. If MYLIB_DEBUG is not defined then MYLIB_ASSERT(X) does nothing. If MYLIB_DEBUG is defined then MYLIB_ASSERT(X) is defined as assert(X). This makes asserts opt-in without messing with NDEBUG.
So my current answer to my question is that it is fine for a library to turn off asserts by default, just don't do it by defining NDEBUG if your interface has any inline functions that contain asserts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With