When to use extern "C" in C++?

pankajt picture pankajt · Aug 18, 2009 · Viewed 44.3k times · Source

Possible Duplicate:
Why do we need extern “C”{ #include <foo.h> } in C++?

I have often seen programs coded like:

extern "C" bool doSomeWork() {
  //
  return true;
}

Why do we use an extern "C" block? Can we replace this with something in C++? Is there any advantage to using extern "C"?

I do see a link explaining this but why do we need to compile something in C when we already have C++?

Answer

Artyom picture Artyom · Aug 18, 2009

extern "C" makes names not mangled.

It used when:

  1. We need to use some C library in C++

    extern "C" int foo(int);
    
  2. We need export some C++ code to C

    extern "C" int foo(int) { something; }
    
  3. We need an ability to resolve symbol in shared library -- so we need to get rid mangling

    extern "C" int foo(int) { something; }
    ///
    typedef int (*foo_type)(int);
    foo_type f = (foo_type)dlsym(handle,"foo")