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

c, c++, include

Solution

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

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

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

Problem

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 ?

Original source