简体   繁体   中英

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)?

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM