user3680
user3680

Reputation: 117

What's the advantage of adding "extern C" in my header files?

I was reading the Section 32: How to mix C and C++ of the C++ FAQ Lite. It says that I should strongly consider adding extern "C" {...} in my header file (adding the appropriate preprocessor directives, of course. That way, I can include the header "without any extern "C" nonsense" in the C++ source file:

// Get declaration for f(int i, char c, float x)
#include "my-C-code.h"

The "nonsense", not-that-easier alternative seems to be this:

extern "C" {
  // Get declaration for f(int i, char c, float x)
  #include "my-C-code.h"
}

Why is the first option preferred? Is it just a matter of style (and the number of chars to type when someone is including them)?

Upvotes: 2

Views: 424

Answers (4)

user195488
user195488

Reputation:

What this accomplishes is that it allows you to use that C header file with your C++ code, because the macro "__cplusplus" will be defined. But you can also still use it with your legacy C code, where the macro is NOT defined, so it won't see the uniquely C++ construct.

#ifdef __cplusplus
extern "C" {
#endif

// all of your legacy C code here

#ifdef __cplusplus
}
#endif

The alternative is to put it with the #include, but if you do it in the C header file then you only need to do it once, plus it's backwards compatible.

Upvotes: 2

spencercw
spencercw

Reputation: 3358

It's a pain for people trying to use your library if you don't include it. If a C header is used from a C++ application without that the user will get compiler or linker errors, which can be particularly confusing for people not familiar with the problem.

Upvotes: 0

Stephen Canon
Stephen Canon

Reputation: 106117

Either you can put the statement once in your header file, or everyone who uses it can put the statement everywhere they include the header file. The former certainly seems like better style to me.

Upvotes: 3

Carl Norum
Carl Norum

Reputation: 224844

Yes, it's just a style thing. But it does make people's lives easier when using your library, so it's probably worth sticking to.

Upvotes: 3

Related Questions