Should I put a C++ macro guard in every header file?

I am writing a little C project. Since I want it to also be included from C++ I thought about using C++ guards to make it work, like:

#ifdef __cplusplus
extern "C" {
// code
#ifdef __cplusplus

In my project I have some headers that must not be included directly from an eventual C++ file using the project. However I am facing the doubt: is putting C++ guards in that header files too a needed precaution?


must not be included directly from an eventual C++ file

Even if they are included indirectly via nested includes, C++ compilation will be applied and without the extern "C" the symbols in the C++ compiled modules will not be the same as those in the C compiled modules that you are linking to.

Apart from that it is good practice and cannot do any harm to include them for interoperability – you may not intend these headers to be used in C++ compilation now, but you cannot tell how they might be used in the future.

If you want to explicitly prevent C++ compilation being applied to a C header, a better solution would be to use:

#if defined __cplusplus
    #error C-only header included in C++ compilation

That way the issue is highlighted at compilation (or pre-processing in fact) rather then causing a linker error that may be harder to interpret when it is telling you that xxx is undefined when you have clearly defined it – but in a different language.