我如何检测我的代码是否被编译为-fno异常?

时间:2021-12-05 07:16:05

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.

我正在编写一个c++库,我想让我的API对无效参数抛出异常,但是当代码用-fno-exception编译时,要依赖断言。

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.

由于该标准没有任何“-fno-exception”的概念,因此解决方案当然可以依赖于编译器。在这种情况下,我对使用g++和clang++的解决方案感兴趣,其他编译器对这个项目并不重要。

Thank you very much

非常感谢你

1 个解决方案

#1


14  

GCC and Clang define the __EXCEPTIONS macro when exceptions are enabled, and do not define it when exceptions are disabled via -fno-exceptions.

GCC和Clang在启用异常时定义__exception宏,在通过-fno-exception禁用异常时不定义该宏。

Example:

例子:

#include <cstdio>
int main() {
#ifdef __EXCEPTIONS
    puts("Exceptions are enabled");
#else
    puts("Exceptions are disabled");
#endif
}

#1


14  

GCC and Clang define the __EXCEPTIONS macro when exceptions are enabled, and do not define it when exceptions are disabled via -fno-exceptions.

GCC和Clang在启用异常时定义__exception宏,在通过-fno-exception禁用异常时不定义该宏。

Example:

例子:

#include <cstdio>
int main() {
#ifdef __EXCEPTIONS
    puts("Exceptions are enabled");
#else
    puts("Exceptions are disabled");
#endif
}