How do I call C programs in C + +?
C + + and C are two completely different ways of compiling links, if the C function is called directly in C + +, the function body will not be found, and the link error is reported. To solve this problem, it is necessary to show in the C + + file which functions are written in C and to be handled in C.
1. Use the extern "C" before referencing the header file, and if you refer to more than one, it looks like this
extern "C"
{
#include "s.h"
#include "T.h"
#include "G.h"
#include "j.h"
};
Then, before calling these functions, you need to declare the function all over again.
2.c++ Call the C function method, the function will be used to re-declare all over again
extern "C"
{
extern void A_app (int);
extern void B_app (int);
extern void C_app (int);
extern void D_app (int);
}
Why do I add extern "C" to a C + + program that calls a function compiled by the compiler?
The C + + language supports function overloading, which does not support function overloading. Functions are compiled in C + + with different names in the library than in the C language. Suppose a C function declares the following:
void foo (int x, int y);
The function is compiled by the C compiler in the library with the name _foo, while the C + + compiler produces names like _foo_int_int to support function overloading and type-safe connections. The C + + program cannot directly invoke the function because the compiled name is different. C + + provides a C connection to swap the specified symbol extern "C" to resolve this problem. For example:
extern "C"
{
void foo (int x, int y);
Other functions
}
or write
extern "C"
{
#include "Myheader.h"
Other C header files
}
This tells the C + + compiler that the function foo is a C connection and should look for names in the library instead of _foo _foo_int_int. The C + + compiler developer has made the extern "C" Processing of the header file of the standard library, so we can refer to these header files directly with # include.
How to call C programs in C + +