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
In Visual StudioIn the left pane, select Configuration Properties, C/C++ and then choose the compiler option category. The topic for each compiler option describes how it can be set and where it is found in the development environment. For more information and a complete list of options, see MSVC compiler options.
(GNU C is a language, GCC is a compiler for that language.Clang defines __GNUC__ / __GNUC_MINOR__ / __GNUC_PATCHLEVEL__ according to the version of gcc that it claims full compatibility with.
__cplusplus. This macro is defined when the C++ compiler is in use. You can use __cplusplus to test whether a header is compiled by a C compiler or a C++ compiler. This macro is similar to __STDC_VERSION__ , in that it expands to a version number.
In the C Programming Language, the #ifdef directive allows for conditional compilation. The preprocessor determines if the provided macro exists before including the subsequent code in the compilation process.
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
}
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