如何检测我的代码是否正在使用-fno-exceptions编译? [英] How do I detect if my code is being compiled with -fno-exceptions?

查看:133
本文介绍了如何检测我的代码是否正在使用-fno-exceptions编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个C ++库,我想让我的API抛出无效参数的异常,但是当用 -fno-exceptions

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.

是否可以在编译时检测是否允许我使用异常处理?
请注意,我正在编写仅标头的库,因此我没有 configure 阶段,也无法访问构建系统来访问只需在命令行上定义一个宏(并且
我不想给用户增加负担)。

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

由于标准没有 -fno-exceptions的概念,当然解决方案可能取决于编译器。在这种情况下,我对同时使用g ++和clang ++的解决方案感兴趣,其他编译器对该项目并不重要。

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.

非常感谢

推荐答案

在启用异常的情况下,GCC和Clang定义了 __ EXCEPTIONS 宏,但未定义它当通过 -fno-exceptions 禁用例外时。

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

示例:

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

这篇关于如何检测我的代码是否正在使用-fno-exceptions编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆