开发者

Programmatically determine whether exceptions are enabled

开发者 https://www.devze.com 2023-03-15 07:51 出处:网络
Most C++ compilers allow for e开发者_JS百科xceptions to be disabled. Is there a way to determine it from the code without using compiler-specific preprocessor macros, such as _CPPUNWIND for MSVC? Idea

Most C++ compilers allow for e开发者_JS百科xceptions to be disabled. Is there a way to determine it from the code without using compiler-specific preprocessor macros, such as _CPPUNWIND for MSVC? Ideally at compile time.


Since WG21 in 2014, there is a recommended macro to use

__cpp_exceptions

It will have the value 199711 if exceptions are supported and the compiler conforms to C++98. Other similar feature macros are shown here.


No. Exceptions are part of C++. The fact that some compilers allow you to disable them is quite irrelevant and the Standard will not provide for you to detect if they're enabled- as far as it's concerned, they're always enabled. If you want to know about implementation-specific behaviour, the only way to go is to ask the implementation.


I'd not burden the runtime with this decision at all. Instead, I'd build two libraries:

libfoo.a
libfoo_exc.a

Then I'd have my configure script determine whether or not we have exceptions, and set the Makefile like this:

ifeq($HAVE_EXCEPTIONS, 1)
  foolib=foo_exc
else
  foolib=foo
endif

libs=$(libs) -l$(foolib)

$(TARGET): $(OBJECTS)
    $(CXX) -o $(TARGET) $(OBJECTS) $(LDFLAGS) $(LIBS)

To determine whether or not you have exceptions you could simply try to build a tiny test program with a trivial try/catch block as suggested in the comments.

To actually build your library, just write conditional code:

#if HAVE_EXCEPTIONS > 0
/* ... */
#else
/* ... */
#endif

And then build two libraries, one with -DHAVE_EXCEPTIONS=0 and one with -DHAVE_EXCEPTIONS=1 or something like that.

That way you have no runtime overhead, and your clients can use whichever library they prefer.

0

精彩评论

暂无评论...
验证码 换一张
取 消