When to use extern “C” in C++? [duplicate]

こ雲淡風輕ζ 提交于 2019-11-27 00:30:21

问题


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


回答1:


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")
    



回答2:


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.



来源:https://stackoverflow.com/questions/1292138/when-to-use-extern-c-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!