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?

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • 1
    @iharob: It could call into external Fortran code, which could throw. – Kerrek SB Aug 31 '16 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. – Trevor Hickey Aug 31 '16 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. – Trevor Hickey Aug 31 '16 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"`? – Richard Critten Aug 31 '16 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. – Iharob Al Asimi Aug 31 '16 at 19:17

1 Answers1

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.

ivaigult
  • 6,198
  • 5
  • 38
  • 66