18

I frequently come across C header files that contain extern "C" guards,
but don't contain any actual functions. For example:

/* b_ptrdiff.h - base type ptrdiff_t definition header */

#ifndef __INCb_ptrdiff_th
#define __INCb_ptrdiff_th

#ifdef __cplusplus
extern "C" {
#endif

#ifndef _PTRDIFF_T
#define _PTRDIFF_T
typedef long ptrdiff_t;
#endif /* _PTRDIFF_T */

#ifdef __cplusplus
}
#endif

#endif /* __INCb_ptrdiff_th */

I know that extern "C" prevents name mangling on functions, but does it also prevent against other interfacing issues on variable and type declarations?

Is the use of extern "C" in the example above meaningless in terms of resulting compatibility?

coredump
  • 37,664
  • 5
  • 43
  • 77
Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • 1
    `extern "C"` does not "prevent" name mangling. It tells the compiler, among other things, to use C-style name mangling. – Pete Becker Nov 04 '15 at 21:25

2 Answers2

23

Some compilers (it's rare) implement name mangling for variables too, not just for functions. In that case, extern "C" may be needed.

Some compilers (it's also rare, but required by the standard) implement language linkage for function types, not just names, so typedef void f(); and extern "C" { typedef void f(); } declare different types.

Also, some maintainers won't notice the absence of extern "C" if they modify the header to add functions.

I recommend you just include it.

  • Are you sure that type linkage is *required* by the standard ? If so, why is it so rare ? – Quentin Nov 04 '15 at 17:58
  • 1
    @Quentin Yes, I am sure. However, there is very little demand from users for this feature, so implementations focus on other features that are in higher demand. –  Nov 04 '15 at 18:00
  • Thank you for acknowledging that "required by the standard" doesn't mean "always available/implemented." – Kyle Strand Nov 04 '15 at 22:05
  • @Quentin: Personally, I consider function type linkage a C++ anti-feature. For instance, that makes technically impossible to use a pointer to a C++ static member as a C pointer to function. The C++ committee makes a hack for `qsort()` and `bsearch()` and they believe the problem does not exist any more. – rodrigo Nov 05 '15 at 08:25
9

No, extern C is not needed there, but it may be convenient to have it in all headers to make sure it is not forgotten when a new function is added.

Stas
  • 11,571
  • 9
  • 40
  • 58