Where is the best place to #ifdef __cplusplus extern "C" {#endif

I would like to know where to put better

#ifdef __cplusplus extern "C" { #endif 

in the header file C.

At the beginning or after everyone else. why?

+7
source share
4 answers

There are no strict rules, but pay attention to the following.

  • The general principle is that each header file takes care of itself (and by itself). Thus, by this principle, there is no need to wrap the header files in extern "C", because the header files will have extern "C" in them (if they need them). So, in the current file, you will place it after another is included.
  • But if you have a whole bunch of headers, you donโ€™t want to add extern โ€œCโ€ and want to make it accessible through one included one, by all means, go ahead and end them in a file from the outside of โ€œCโ€.

Just be aware that the idea of โ€‹โ€‹extern "C" is that it forces the compiler to generate C friendly communications. Otherwise, code compiled with the C ++ compiler looks for malformed names for matching in archives compiled with the C compiler, and not can find them.

+9
source

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

So, obviously, you want to use it only in your things.

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_ 
+9
source

extern "C" affects how code is compiled. Headers that are designed to compile both C and C ++ will control extern "C" . You should never wrap the #include directive in an extern "C" block: if the header that was involved was compiled in both cases, when your directive is redundant, and if it was not intended to be used as it is an error.

+1
source
  • extern "C" affects communication. When C ++ functions are compiled, they have different names, so overloading in C ++ is possible. Thus, the function name is changed based on the types and number of parameters, so two functions with the same name will have two different symbolic names.

  • The code inside extern "C" is still C ++ code. There are restrictions on what you can do in the external block "C", but they are all related to binding.

+1
source

All Articles