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

杀马特。学长 韩版系。学妹 提交于 2019-11-28 04:33:34

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

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.

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