When to use extern "C" in C++? [duplicate]
Asked Answered
T

2

25

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++?

Teal answered 18/8, 2009 at 6:30 Comment(2)
Duplicate of #68394Aurelea
related: https://mcmap.net/q/14733/-what-is-the-effect-of-extern-quot-c-quot-in-c #718229 #496948Chandlery
T
38

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")
    
Typographer answered 18/8, 2009 at 6:30 Comment(0)
C
17

One place where extern "C" makes sense is when you're linking to a library that was compiled as C code.

extern "C" {
  #include "c_only_header.h"
}

Otherwise, you might get linker errors because the library contains the functions with C-linkage (_myfunc) but the C++ compiler, which processed the library's header as C++ code, generated C++ symbol names for the functions ("_myfunc@XAZZYE" - this is called mangling and different for each compiler).

Another place where extern "C" is used is to guarantee C linkage even for functions written in C++, eg.

extern "C" void __stdcall PrintHello() {
  cout << "Hello World" << endl;
}

Such a function can be exported to a DLL and will then be callable from other programming language because the compile will not mangle its name. If you added another overload of the same function, eg.

extern "C" void __stdcall PrintHello() {
  cout << "Hello World" << endl;
}
extern "C" void __stdcall PrintHello(const char *name) {
  cout << "Hello, " << name << endl;
}

Most compilers would then catch this and thus prevent you from using function overloads in your DLL-public functions.

Casto answered 18/8, 2009 at 6:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.