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

2

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?

Etamine answered 4/11, 2015 at 16:2 Comment(1)
extern "C" does not "prevent" name mangling. It tells the compiler, among other things, to use C-style name mangling.Blossom
P
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.

Prater answered 4/11, 2015 at 16:16 Comment(4)
Are you sure that type linkage is required by the standard ? If so, why is it so rare ?Polyester
@Polyester 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.Prater
Thank you for acknowledging that "required by the standard" doesn't mean "always available/implemented."Orthotropic
@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.Afghanistan
B
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.

Burnish answered 4/11, 2015 at 16:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.