Is it required to add 'extern C' in source file also?

Since you mean

extern "C" { ... }

style guards, these declare some functions to be of "C" linkage, rather than "C++" linkage (which typically has a bunch of extra name decoration to support things like overloaded functions).

The purpose, of course, is to allow C++ code to interface with C code, which is usually in a library. If the library's headers weren't written with C++ in mind, then they won't include the extern "C" guards for C++.

A C header written with C++ in mind will include something along the lines of

#ifdef __cplusplus
extern "C" {
#endif

...

#ifdef __cplusplus
}
#endif

to make sure C++ programs see the correct linkage. However, not all libraries were written with C++ in mind, so sometimes you have to do

extern "C" {
#include "myclibrary.h"
}

to get the linkage correct. If the header file is provided by someone else then it's not good practice to change it (because then you can't update it easily), so it's better to wrap the header file with your own guard (possibly in your own header file).

extern "C" isn't (AFAIK) ANSI C, so can't be included in normal C code without the preprocessor guards.

In response to your edit:

If you are using a C++ compiler, and you declare a function as extern "C" in the header file, you do not need to also declare that function as extern "C" in the implementation file. From section 7.5 of the C++ standard (emphasis mine):

If two declarations of the same function or object specify different linkage-specifications (that is, the linkage-specifications of these declarations specify different string-literals), the program is ill-formed if the declarations appear in the same translation unit, and the one definition rule applies if the declarations appear in different translation units. Except for functions with C++ linkage, a function declaration without a linkage specification shall not precede the first linkage specification for that function. A function can be declared without a linkage specification after an explicit linkage specification has been seen; the linkage explicitly specified in the earlier declaration is not affected by such a function declaration.

I'm not convinced it's good practice though, since there's the potential for the linkage specifications to diverge by accident (if, for example, the header file containing the linkage specification isn't included in the implementing file). I think it's better to be explicit in the implementation file.


They only need to go in anything that is included by other source files.

With some idioms you'll find people including source files.


They should be added to all files, that get included in other files.

Normally, one doesn't include source files.

Tags:

C++

C