Current location - Education and Training Encyclopedia - Education and training - How does discuz x2 call the value of a field in the database with template syntax?
How does discuz x2 call the value of a field in the database with template syntax?
1. For non-class member functions in C++, just add extern "c" before the function declaration, which is usually located in the header file. Of course, you can also put declarations and function definitions together in cpp. If there is no declaration, you can directly add extern "c" before the definition.

2. For the member function of C++ class, you need to make another cpp file to wrap the function to be called.

For the above two examples, please refer to the article on how to call C++ code in C.

To realize code call C in C++, the specific operation is as follows:

For the function code in C, either modify the header file of C code and add Extern "C" in the declaration when it is included in C++ code, or redeclare C function in C++ code and add Extern "C" header when redeclaring.

From the above explanation, I understand that adding the Extern "C" header must be added to the C++ code file to be effective.

Let's analyze the essential reason of this phenomenon:

C compiler compiles functions without function type information, only function symbol names. For example, the C compiler compiles the function int a(float x) into a symbol such as _a, and the C connector can connect successfully as long as it finds the symbol calling the function. It assumes that the parameter type information is correct, which is the shortcoming of C compiler connector. In order to realize function overloading, the C++ compiler will bring the type information of the function when compiling. For example, he can compile the above a function into a symbol, such as _a_float. In order to realize overloading, note that it still has no return value information, which is one of the reasons why C++ doesn't support using the return value of a function to distinguish function overloading. Of course, the way the function user handles the function return value (such as ignoring it) is also an important reason.

Based on the above, when C calls C++, the call to C++ class needs to be encapsulated into a C function for C call, so the function of Extern "C" is to let the compiler know this, and then compile the encapsulated function in C language (usually the encapsulated function is compiled by C+ compiler in C++, and after using Extern "C", the compiler compiles the encapsulated interface in C way, of course, for the part of C language, After compiling the C++ interface part and the C part respectively, you can call C++ by connecting them. On the contrary, when C++ calls a C function, the function of Extern "C" is to let the C++ connector find the symbol of calling function in a C way, that is, use _a instead of _a_float to find the calling function.