namespace someNameSpace {
extern "C" void doSomething()
{
someOperations();
}
}
I want to run doSomething()
in both C++ and C environment.
Is someNameSpace
still encapsulating doSomething()
if I expose it to extern "C"
linkage?
Is there a good way to share functions between C++ and C while avoiding polluting global namespace on C++ side?
Edit: Because this code is primarily used in C++ mode, while the C linkage is for test use only, I guess this is a better way to do it.
namespace someNameSpace {
#ifdef COMPILE_FOR_C_LINKAGE
extern "C"
#else
extern "C++"
#endif
{
void doSomething()
{
someOperations();
}
}
}
Your code works, but you should beware that all functions that have
extern "C"
linkage share the same space of names, but that is not to be confused with the C++ notion of "namespace": Your function is reallysomeNameSpace::doSomething
, but you cannot have any otherextern "C"
function with unqualified namedoSomething
in any other namespace.See 7.5/6:
Your company's or project's global style arbiters should be able to advise you on a suitable naming policy for your code base.
Just piece of code to illustrate behavior stated in Kerrek SB answer
Live at http://ideone.com/X26wfR