C + + is developed on the basis of C + + language. In a way, we can consider C + + as an extension of C. In essence, both of the http://www.aliyun.com/zixun/aggregation/18278.html "> data types and function invocation conventions are consistent, so C and C + + mixed compilation is also a natural thing."
The difference is only that the name of the compiled function is different ──c simply use the function name without considering the number or type of parameters, and the C + + compiled function name always takes the list of parameter types as part of it. In spite of this, C + + provides a special mechanism for declaring C functions, which means that a C + + program can declare and invoke functions directly.
C + + Call function
The following is an example of C-function Csayhello () called by a C + + program. Because the function uses extern "C" when declared within a C + + program, the call can be made directly:
/* Cpp2c.cpp *
#include <iostream>
extern "C" void Csayhello (char *str);
int main (int argc,char *argv[])
{
Csayhello ("Hello from CPP to C");
return (0);
}
The C function does not require any special handling, and its code is as follows:
/* CSAYHELLO.C *
#include <stdio.h>
void Csayhello (char *str)
{
printf ("%s\n", str);
}
The following three commands compile the above two files and link them to an executable file. Because of the flexibility of GCC and g++, there are many ways to accomplish this task, but these three commands are probably the most common:
$ g++-C Cpp2c.cpp-o CPP2C.O
$ gcc-c Csayhello.c-o csayhello.o
$ gcc cpp2c.o csayhello.o-lstdc++-o cpp2c
Note that it is necessary to specify the C + + standard library at the end of the link because we are using GCC instead of the g++ called Linker. If you are using g++, the C + + standard library is linked by default.
The most common practice is to put the function declaration in the header file, and then include all content in the extern "C" declaration block. The contents of the file appear as follows:
extern "C" {
int Mlimitav (int lowend, int highend);
void Updatedesc (char *newdesc);
Double getpct (char *name);
};