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

旧街凉风 提交于 2019-12-30 03:06:26

问题


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


回答1:


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
}


来源:https://stackoverflow.com/questions/25259070/how-do-i-detect-if-my-code-is-being-compiled-with-fno-exceptions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!