The original text can not be tested, reproduced link: http://blog.csdn.net/owldestiny/article/details/5772916
Please inform me if you find the original text, I will update it in time.
This code is often seen in the CPP code:
#ifdef __cplusplusextern "C" {#endif//section of code #ifdef __cplusplus} #endif
What does this kind of code mean? First of all, __cplusplus is a custom macro in CPP, then the definition of this macro means that this is a CPP code, that is, the above code means: If this is a piece of CPP code, then add the extern "C" {and} to process the code in it.
To understand why the extern "C" is used, you have to start with the overloaded handling of the function from CPP. In C + +, in order to support overloading mechanism, in compiling the generated assembly code, the name of the function to do some processing, such as the return type of the function and so on. In C, it's just a simple function name that doesn't include any other information. That is, C + + and C handle the resulting function names differently. The purpose is to implement the problem of mutual invocation between C and C + +.
The realization of c.h
#ifndef _c_h_
#define _c_h_
#ifdef __cplusplus
extern "C" {
#endif
void C_fun ();
#ifdef __cplusplus
}
#endif
#endif
-----------------------------------
The realization of C.C
# include "C.h"
void C_fun ()
{
}
------------------------------------
Call the C_test () in C.C in Cpp.cpp
The realization of Cpp.cpp
# include "C.h"
int main ()
{
C_fun ()
}
Where __cplusplus is a reserved macro definition for the C + + compiler. This means that the C + + compiler thinks the macro is already defined.
So the key is extern "C" {}
extern "C" is to tell C + + compile the device in parentheses is compiled according to the C obj file format, to connect the word according to C's naming rules to find.
==========================
So in C, how do you call the function Cpp_fun () in C + +?
Because C + + is available first, it can only be considered in C + + code.
The addition of a function or variable in C + + may be dropped by a file in a, then it should be written with extern "C" {}
Just add the code, and the header file is added, because it might be called in C + +.
--------------------------------------
The realization of Cpp.h
#ifndef _c_h_
#define _c_h_
#ifdef __cplusplus
extern "C" {
#endif
void Cpp_fun ();
#ifdef __cplusplus
}
#endif
#endif
.-------------------------------------------
The realization of Cpp.cpp
extern "C" {//Tell c+++ compiler, the extension number is compiled according to C's naming rules
void Cpp_fun ()
{
.....
}
Summarize
C and C + + treat functions differently. extern "C" is a means to enable C + + to invoke C-writing library files, and if you want to use C as the compiler prompts to handle functions, then use extern "C" to illustrate.
#ifdef _cplusplus (EXT)