In my header file, foo.h, I have:
#ifdef __cplusplus
extern "C" {
#endif
int foo(int x);
#ifdef __cplusplus
}
#endif
Now, in foo.cpp, should I also use extern "C", and define:
#include "foo.h"
extern "C" {
int foo(int x);
};
? Or is the declaration enough to ensure C-linkage (no name mangling)?
Marking the declaration by
extern "C"is enough.If the translation unit containing the declaration of your function has it with
extern "C", the compiler will respect this when it finally encounters the implementation - and use a non-mangled symbol inside the object file.See this on GodBolt.
Remember, though, that if your implementation does not see your header, nothing will make it extern "C" if you don't do so explicitly.