extern "C"

来源:互联网 发布:上市公司研发费用数据 编辑:程序博客网 时间:2024/06/04 05:42

msdn中这样解释 extern “C”

C++ uses the same calling convention and parameter-passing techniques as C, but naming conventions are different because of C++ decoration of external symbols. By causing C++ to drop name decoration, the extern "C" syntax makes it possible for a C++ module to share data and routines with other languages.The following example declares prn as an external function using the C naming convention. This declaration appears in C++ source code.extern "C"{    void prn();}To call functions written in Fortran (or MASM), declare the function as you would in C and use a "C" linkage specification. For example, to call the Fortran function FACT from C++, declare it as follows:extern "C" { int __stdcall FACT( int n ); }The extern "C" syntax can be used to adjust a call from C++ to other languages, or to change the naming convention of C++ routines called from other languages. However, extern "C" can be used only from within C++. If the C++ code does not use extern "C" and cannot be changed, you can call C++ routines only by determining the name decoration and generating it from the other language. You can always determine the decoration by using the DUMPBIN utility. Use this approach only as a last resort, because the decoration scheme is not guaranteed to remain the same between versions.Use of extern "C" has some restrictions: You cannot declare a member function with extern "C".You can specify extern "C" for only one instance of an overloaded function; all other instances of an overloaded function have C++ linkage. For more information on the extern "C" linkage specification, seeLinkage Specifications in C++ Language Reference.

可以看出,extern “C” 主要用来解决命名粉碎的问题.
而且 extern “C” 只能在c++中用.
只有c++全局函数可以用extern “C”, 成员函数无法用extern “C”修饰.
因为没有命名粉碎,所以没有函数重载, 在c中,函数是不能重名的.

正因为extern “C”是c++特有的修饰, 在cpp工程函数声明时,才需要如下代码

#if defined(__cplusplus)extern "C"{#endif// Function declarations#if defined(__cplusplus)}#endif 

上面这种兼容的头文件写法,可以在c++和c工程中公用, 不用给c++或c工程单独准备一份不同的头文件.

0 0