Search code examples
c++cheader-filesexternextern-c

Is there any reason to use extern "C" on headers without methods?


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?


Solution

  • 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.