17

I have to link two libraries, say A and B. Some of the files are common in both libraries. So, I declare functions in library A inside a namespace, say abc. So, in A and B, a function func looks like below:

[ in A]

    namespace abc {
    extern "C" void func();
    }


[in B]

    extern "C" void func();

While building the project, compiler throws linking errors saying multiple definitions of function func. Isn't the function func in A inside the namespace or is there some problem with extern "C" functions. If there is, then how can I differentiate them both?

sbi
  • 219,715
  • 46
  • 258
  • 445
Dharmendra
  • 384
  • 1
  • 5
  • 22

1 Answers1

26

When you use Extern "C" you are turning off name mangling so you lose the namespace information as C has no such concept. This causes a duplicate definition.

rerun
  • 25,014
  • 6
  • 48
  • 78
  • 1
    Note, however, that name mangling may not be turned off for the C preprocessor. In Visual C++ 2010 the value of the `__FUNCTION__` macro remains the fully qualified identifier even under `extern "C"`, e.g. "your::name". This will fall on your feet when calling macros in namespaces that use predefined macros like `__FUNCTION__`, `__PRETTY_FUNCTION__` or `__func__`. In my case (exporting C stubs from a DLL) it did ;-) – Andreas Spindler May 03 '12 at 09:42