简体   繁体   中英

Where is the best place to put the #ifdef __cplusplus extern “C” { #endif

I would like to know where is better to put the

#ifdef __cplusplus
extern "C" {
#endif

in a C header file.

At the beginning or after all the other includes. why ?

There are no strict rules on this, but note the following.

  1. The general principle is that each header file takes care of itself (and is self sufficient). So, by this principle, there would be no need to wrap the header files in a extern "C", because the header files would have an extern "C" in them (if they need one). So, in the current file, you would place it after the other includes.
  2. But if you do a have a whole bunch of headers, that you don't want to add an extern "C" to, and want to make available through a single include, by all means, go ahead and wrap them up in a file wide extern "C".

Just know that the idea behind extern "C" is that it makes the compiler generate C friendly linkage. Otherwise, code compiled with a C++ compiler looks for mangled names to link against in archives compiled with a C compiler, and can't find them.

This construct is used to make your names available to a C linker (short explanation)

So obviously you want to use it around your stuff only.

Like this :

#ifndef MY_INCLUDE_H_ // include guard
#define MY_INCLUDE_H_

#include <...> // dependencies
#include "..."

#ifdef __cplusplus
extern “C” {
#endif

// ... your types, methods, variables

#ifdef __cplusplus
}
#endif

#endif // MY_INCLUDE_H_
  • extern "C" affects linkage. When C++ functions compiled they have their names varies, that's why overloading in C++ is possible. So, function name gets modified based on the types and number of parameters, so two functions with the same names will have two different symbol names.

  • Code inside an extern "C" is still C++ code. There are limitations on what you can do in an extern "C" block, but they're all about linkage.

extern "C" affects the way that code is compiled. Headers that are designed to be compiled both as C and as C++ will manage extern "C" themselves. You should never wrap a #include directive in an extern "C" block: if the header involved was designed to be compiled both ways your directive is redundant, and if it wasn't designed to be used both ways it's an error.

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