【问题标题】:How do I detect if my code is being compiled with -fno-exceptions?如何检测我的代码是否使用 -fno-exceptions 编译?
【发布时间】:2014-08-12 08:00:13
【问题描述】:

我正在编写一个 C++ 库,我想让我的 API 为无效参数抛出异常,但在使用 -fno-exceptions 编译代码时依赖断言。

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

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

非常感谢

【问题讨论】:

    标签: c++ g++ clang++


    【解决方案1】:

    GCC 和 Clang 在启用异常时定义 __EXCEPTIONS 宏,而在禁用异常时不定义它通过 -fno-exceptions

    例子:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-09
      • 2014-12-07
      • 2017-01-20
      • 2018-02-06
      • 1970-01-01
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多