include C headers in C++ as noexcept

Viewed 178

Is there a way (compiler extensions are acceptable) to include C headers and mark included C functions as noexcept, but without modifying headers?

For example, I have a C library and its header header.h. No C++ callback will be passed into it so it never throws. Can I mark the included C functions as noexcept or tell compiler that they never throw, so that the compiler doesn't have to generate unused code and enable some possible optimizations for callers? Note that the C++ code using the C library should still be able to use exceptions (so disabling exceptions for the entire program is not an option).

extern "C" {
#include "header.h" // Is there a way to mark included C functions here as noexcept?
}
1 Answers

There isn't a way that you're looking for.

What you could do for example, is not use the header at all. Write your own header where the functions are marked noexcept. This of course has the drawback that you must maintain the new header and keep it up to date with changes in the library.

Or - if you can give up the premise of not modifying the header - you can add noexcept to the header while still keeping it compatible with C by wrapping the C++ features in macros. This is how for example C standard libraries are written, as they are inherited by C++ standard libraries.

Related