4

I have some C code being called from C++.
The header resembles the following:

#ifndef CLibH
#define CLibH

#ifdef __cplusplus
extern "C" {
#endif

//C API
void foo(void);
// ...

#ifdef __cplusplus
}
#endif

#endif

Since I'm already using extern C,
is there any benefit to adding the nothrow compiler attribute?

#ifndef CLibH
#define CLibH

#ifdef __cplusplus
extern "C" {
#endif

//C API
void foo(void) __attribute__((nothrow));
// ...

#ifdef __cplusplus
}
#endif

#endif

Does extern C make this redundant?
Are there still advantages to applying it under these circumstances?

5
  • 1
    @iharob: It could call into external Fortran code, which could throw. Commented Aug 31, 2016 at 18:29
  • @iharob Exactly. So the compiler should optimize just the same with or without the attribute? I wasn't sure if there were some subtleties with libraries, or if C code could call back into C++, etc. Commented Aug 31, 2016 at 18:29
  • 1
    @KerrekSB So "extern C" does not guarantee "no throw". A function can still throw if it is wrapped in "extern C". That makes sense. Commented Aug 31, 2016 at 18:31
  • extern "C" can call straight into C++ code marked as extern "C". So the questions becomes can exceptions propagate out of a C++ function marked as extern "C"? Commented Aug 31, 2016 at 18:43
  • I feel very stupid. I myself wrote a c++ plugin system which of course used c to construct classes. Contructors can throw and I used new of course, so it's not redundant at ll. In fact you can externalize any c++ function and use stl, the new operator (which does throw exceptions). The only thing extern "C" does is prevent name mangling. Commented Aug 31, 2016 at 19:17

1 Answer 1

0

Yes, it does. From gcc documentation:

For example, most functions in the standard C library can be guaranteed not to throw an exception with the notable exceptions of qsort and bsearch that take function pointer arguments.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.