C + + as a set of extensions of language, almost all C programs can be compiled and run in C + +, but note that C program may use keywords in C + + as variables, such as in C: int class = 0; But that doesn't work in C + +. For convenience, we can call a function (c) in a class, or you can use an object (c + +) in a function.
When mixing C and C + +, object-oriented features can be lost, such as using C's function library in C + + programs, where C functions can be repackaged as an easy-to-use class, and the return value of the C function can generally be used as a member of the class .
C + + supports function overloading through name mangling , but the C language does not support it as a redefinition of overloads. By default, the C + + compiler executes name mangling for each function, generating a strange function name, but if you need to link a C-language function library at this point, the C + + compiler fails because it cannot find these strange names. Therefore, you must explicitly tell the C + + compiler that this function is named with a language specification by using the extern "language" description, whose syntax is:
extern "Language" void func1 ();
extern "Language" void Func2 ();
Or:
extern "Language" {
void Func1 ();
void Func2 ();
}
Such as:
extern "C" void func (int i); /* indicates that func (int i) is an external C function that tells the C + + compiler that the code is written in C * /
The use of extern is typically in a header file, such as a library of functions written in a C language now, This library may have a. h file, at which point we can write a new header file. HPP, the original header file is placed in the extern module, indicating that the functions defined in the header file are written in the C language:
New_head.hpp
extern "C"
{
#include "Old_head.h"
}
Also, we can choose whether to use a C module or a C + + module through conditional compilation : C + + compiles a symbolic __cplusplus, and C compiles the symbol is undefined, so you can usually define the following form of header file:
#ifndef __cplusplus
extern "C"
{
#endif//__cplusplus
void Func1 ();
void Func2 ();
#ifndef __cpluscplus
}//extern "C"
#endif//__cpluscplus
The code above ensures that both C and C + + programmers can use FUNC1 () and Func2 () correctly.
Mixed use of C and C + +