问题
I'm writing a C++ library and I would like to make my API throw exceptions for invalid parameters, but rely on asserts instead when the code is compiled with -fno-exceptions
.
Is there a way to detect at compile-time if I'm allowed to use exception handling?
Note that I'm writing a header-only library, so I don't have a configure
phase and I don't have access to the build system to simply define a macro on the command line (and
I don't want to add burden to the user).
Since the Standard doesn't have any concept of "-fno-exceptions", of course the solution could be compiler-dependent. In this case I'm interested in solutions that work with both g++ and clang++, other compilers are not important for this project.
Thank you very much
回答1:
GCC and Clang define the __EXCEPTIONS
macro when exceptions are enabled, and do not define it when exceptions are disabled via -fno-exceptions
.
Example:
#include <cstdio>
int main() {
#ifdef __EXCEPTIONS
puts("Exceptions are enabled");
#else
puts("Exceptions are disabled");
#endif
}
来源:https://stackoverflow.com/questions/25259070/how-do-i-detect-if-my-code-is-being-compiled-with-fno-exceptions