A classic example
The most classic example of using preprocessing and macro definition is to add a header file to avoid the header file being compiled twice. In this case, there is a file headerfile. h. It is included in headerfile1.h and also included in headerfile2.h. Now there is a CPP file, implement. CPP contains headerfile1.h and headerfile2.h:
# Include "headerfile1.h" # Include "headerfile2.h" |
Assume that headerfile. h defines a global variable iglobal.
During compilation, the compiler compiles the headerfile twice and finds that iglobal is defined twice. In this case, a variable redefinition compilation error occurs.
The traditional solution is to use # ifdef and # endif to avoid repeated compilation of header files. In the preceding example, you only need to add the following lines:
# Ifndef smartnose_2002_6_21_headerfile_h # Define smartnose_2002_6_21_headerfile_hInt iglobal; # Endif |
After careful consideration of the macro definition above, we will find that when the compiler compiles the headerfile once. H and later, the macro smartnose_2002_6_21_headerfile_h is defined, and headerfile will be used later. the Int iglobal line will be skipped during compilation of H. Of course, the macro smartnose_2002_6_21_headerfile_h can be defined at will, but the macro itself cannot be the same as the macro defined in other files, therefore, MFC always uses a random macro with a very long length in an automatically generated file, but I don't think this is necessary. I suggest you add some meaningful information to this macro, for example, the author, the file name, the file creation time, and so on, because we sometimes forget to add this information to the comment.
In VC. net, we will not see these macro definitions any more, because a preprocessing command is generally used here:
You only need to add this command at the beginning of the header file to ensure that the header file is compiled once. This command is actually available in vc6, but it is not widely used in consideration of compatibility.