First, let's briefly describe two points:
1. The basic unit of compiler compilation is a C file or Cpp file, which is not the correct file for compilation.
2. extern "C" can only be processed by the C ++ compiler. The C compiler does not recognize this flag.
Use the sample code in the previous article. The Code is as follows:
/* CppHeader. h */
# Ifndef CPP_HEADER
# Define CPP_HEADER
Extern "C" void print (int I );
# Endif CPP_HEADER
/* CppHeader. cpp */
# Include "cppHeader. h"
# Include <stdio. h>
# Include <iostream. h>
Void print (int I)
{
Printf ("cppHeader % d \ n", I );
}
/* C. c */
Extern void print (int I );
Int main (int argc, char ** argv)
{
Print (3 );
Return 0;
}
There are three files: CppHeader. h, CppHeader. cpp, and c. c. Use the following command to manually compile and link:
Cl/c/Tp CppHeader. cpp
Cl/c/Tc c. c
Link c. obj CppHeader. obj
The c.exe file is generated and runs normally.
Now, remove # include "CppHeader. h" in cppHeader. cpp. In the compilation process, the command is the same, and the c.exe file cannot be generated. The error message is:
C. obj: error LNK2001: unresolved external symbol _ print
C.exe: fatal error LNK1120: 1 unresolved externals
After comparison, we find that the program can compile the link normally by adding an extern "C" void print (int I) to the CppHeader. cpp file. Extern "C" tells the C ++ compiler that you compile the print () function in the C method. In this way, the C ++ compiler compiles the print (int I) function into the _ print symbol, which can be seen using the dumpbin tool.
Here is a summary of the functions of extern "C:
In a C ++ source file, if there is an extern "C" statement, there may be two situations:
1. if the function modified by extern "C" is implemented in this file, the C ++ compiler will compile the function in C mode, other functions in this file call this function in C mode, or use C as a link.
2. if the function modified by extern "C" is implemented in other files, the function in this file calls this function in the method of C, or links in the method of C.
From the canmeng50401 Column