Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect if my code is being compiled with -fno-exceptions?

Tags:

c++

g++

clang++

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

like image 644
gigabytes Avatar asked Aug 12 '14 08:08

gigabytes


People also ask

How do I find the compiler in Visual Studio?

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.

Does clang define __ GNUC __?

(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.

What is __ Cplusplus in C++?

__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.

What is #if defined in C?

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.


1 Answers

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
}
like image 60
Brian Bi Avatar answered Oct 04 '22 15:10

Brian Bi