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