"Reprint" C/C + + preprocessor

Source: Internet
Author: User

Transferred from: http://www.cnblogs.com/lidabo/archive/2012/08/27/2658909.html

the process of compiling a program for C + + compiles is preprocessing, compiling, and linking. a preprocessor is a program that processes source files based on pre-processing instructions before the program source files are compiled. Preprocessor directives are identified at the beginning of the # number and do not contain semicolons at the end. Pre-processing commands are not part of the C + + language itself, and they cannot be compiled and linked directly. An important feature of the C + + language is the ability to use preprocessing directives and features that have preprocessing. The pre-processing capabilities provided by C + + include file inclusion, macro substitution, conditional compilation, and so on.

1. The file contains
The preprocessing directive # # is used to contain header files in two forms: #include <xxx.h>, #include "xxx.h".
The angle brackets represent the files that are contained in the system directory. If the included file is not necessarily in the system directory, it should be in double quotation marks.
You can indicate the file path and file name in the double quotation mark form. If the absolute path is not given in double quotation marks, the default is the file in the user's current directory, when the system first looks for the file to be included in the user's current directory, and then finds it in the system directory if it is not found.
For the user to write their own header files, it is appropriate to use double quotation marks form. For a system-provided header file, the contained file can be found either in angle brackets or in double quotation marks, but is clearly more straightforward and more efficient in the form of angle brackets.
./indicates the current directory,.. /represents the parent directory of the current directory.

2. Macro Replacement
① macro Definition
The function of a macro definition is usually to represent a long code sequence with a short name. Macro definitions include parameterless macro definitions and two types of macro definitions with parameters. The code sequence represented by the macro name and macro parameter can be anything of any significance, such as type, constant, variable, operator, expression, statement, function, code block, and so on.However, it is important to note that the macro name and macro parameters must be valid identifiers, and the contents and meanings of the macros must always be independent and invariant before and after the macro expansion, and cannot be interpreted and executed separately.
No parameter macro definition. A user-specified identifier, called a macro name, represents a sequence of code, which is a generic form of a # define identifier code sequence. Where the identifier after # define is called the macro definition name (the macro name), you can have several spaces, tabs, but no other characters, separated by whitespace between the macro name and the code sequence, before the macro defines a # define.
With the parameter macro definition. With the parameter macro definition to further expand the ability to define a parameterless macro, the macro expands to replace both the macro name and the macro parameter. The general form of a macro definition with parameters is a # define identifier (parameter table) code sequence, where the parameters in the parameter table are separated by commas, and the parameters in the parameter table must be included in the code sequence.When you define a macro with parameters, there is no white space between the macro name and the left parenthesis, which should be immediately followed by a macro definition without parameters. The number of actual arguments supplied with a parameter macro call must be the same as the number of formal parameters in the macro definition.
The valid range for a macro definition is called the scope of the macro name, and the scope of the macro name begins at the end of the macro definition to the end of the source code file where it resides. The scope of the macro name is not affected by the structure of the sub-program. If you need to terminate the scope of the macro name, you can use the preprocessing directive #undef to add the macro name.
Macro names are generally capitalized in order to distinguish them from variable names. If necessary, the macro name can be repeated and defined, and the original meaning of the macro name is replaced by the new meaning.
The macro definition code sequence must be "" paired and cannot take the string "" apart. For example, the # define name "Vrmozart" is not legal and should be the # define name "Vrmozart".
A macro definition code sequence can refer to a macro name that has already been defined, that is, the macro definition can be nested.
② Multi-line macros
The macro definition must be a separate line in the source file, and the line break is the end flag for the macro definition, so the macro definition ends with a newline, and does not require symbols such as semicolons as delimiters. If the code sequence in a macro definition is too long and a row is not enough, you can use the continuation method.The continuation line is to type the symbol before you type the carriage return, note that the carriage return must be followed by the symbol \, the middle cannot insert other symbols, and of course the last line of the code sequence cannot have \ at the end.Note A multiline macro can be called only on a single line when it is called, and cannot be used in an expression or as a function parameter.
③ macro Expansion
When the preprocessor processes a macro definition, the macro is expanded (that is, the macro is replaced). Macro substitution first replaces all macro names in the source file that appear in the macro definition with the code sequence they represent, and then replaces the macro parameter name in the code sequence with the macro argument name if it is a parameter macro.The macro substitution works only as a sequence of code characters, without any syntax checking or intermediate calculations, and all other operations are done after the replacement. If the macro is not defined properly, the error will not be discovered until the pre-processing compilation phase.
The macro name in the source code and the macro definition in the code sequence must be an identifier to be substituted, that is, replace only the identifier, not replace something else, such as comments, string constants, and the name of the macro or macro parameter that appears within the identifier is not replaced. For example:
#define NAME Vrmozart, the macro name in source code//name,/*name*/, "name", and My_name_blog name is not replaced.
#define BLOG (name) my_name_blog= "name", the macro definition of the macro parameter name in the code sequence is also not replaced.
If you want the macro parameter names that appear in the identifiers in the macro definition code sequence to be replaced, you can add a connector between the macro parameter name and the identifier # #, and the macro parameter name and the connector # during the macro substitution # #一起将被替换为宏实参名。 # #用于把宏参数名与宏定义代码序列中的标识符连接在一起, form a new identifier. For example:
#define BLOG (name) my_# #name, blog (vrmozart) represents My_vrmozart
#define BLOG (name) name# #_ Blog,blog (vrmozart) represents Vrmozart_ Blog
#define BLOG (name) my_# #name # #_blog, blog (vrmozart) means My_vrmozart_ blog
If you want the macro parameter names in the macros definition code sequence to be replaced with the string form of the macro argument name (that is, double quotation marks at both ends of the macro argument name) instead of the macro argument name, you can add a symbol before the macro parameter name in the macro definition code sequence#。 #用于把宏参数名变为一个字符串形式. For example:
#define STR (name) #vrmozart, str (vrmozart) indicates "Vrmozart"
When the macro parameter is another macro, it is important to note that the macro defines a code sequence that is useful for # or # #的宏参数是不会再展开.
④ the independence of the macro
As stated in the macro definition, the contents and meanings of macro names and macro parameter names must always be independent and remain constant before and after the macro expansion, and cannot be interpreted and executed separately. The reason for this is that, when the macro is called, replace the macro name with the code sequence defined by the macro, and replace the macro parameter name with the macro argument name. Once replaced, the code sequence defined by the macro is naturally connected to the code adjacent to the source file, and the macro argument name is naturally connected to the code adjacent to the code sequence.The independence of the code sequence and macro argument names defined by the macro does not necessarily persist. For example:
#define SQR (x) x*x, you want to implement the square calculation of an expression.
For a macro call P=sqr (y), you can get the desired macro expansion p=y*y. But for a macro called Q=SQR (U+V), the resulting macro expansion is q=u+v*u+v. Obviously, the outcome of the latter is not what the programmer wants. To be able to maintain the independence of the macro argument name, enclose the formal parameter in the macro definition. Further, in order to guarantee the independence of the macro name invocation, the macro definition code sequence as a calculation should also be bracketed. The SQR macro definition is rewritten into a # define SQR (x) ((x) * (x)) is the correct macro definition.
⑤ the difference between a macro call and a function call
function calls are performed while the program is running, and macro expansion is done during the preprocessing phase of the compilation, the function calls occupy the program run time, the macro calls take up only the compile time, the function calls have type requirements for the arguments, and the macro calls there is no concept of a type between the macro-defined formal parameters A function call can return a value, and a macro call obtains the desired code sequence. In addition, when the function is called, the argument expression is evaluated independently before the function body is executed. A macro call is an actual parameter sequence substitution form parameter.
⑥ Pre-defined macros
__date__, a string constant type that represents the compilation date of the current source file, and the output format is MMM dd yyyy (if May 27 2006).
__time__, a string constant type that represents the compilation date of the current source file, and the output format is HH:MM:SS (such as 09:11:10).
__file__, a string constant type that represents the current source file name and contains the file path.
__line__, an integer constant type that represents the line number in the current source file.
__function__, a string constant type that represents the current function name.
These scheduled macros are useful when debugging a program, because you can easily know the line that the program runs to that file, which is the function.
In addition to defining macros using # define at the beginning of the source file, users can also define macros in the compiler project properties "preprocessor" property page. This macro definition supports numbers and strings in the general form: identifiers = Numbers or string constants, and if omitted = and subsequent content, the macro name identifies defaults as the integer 1. The way to define a macro is to enter the content of the macro definition in the preprocessor definition property, separating multiple macro definitions with semicolons. The macro definition in the preprocessor definition is processed before the macro definition in the source file is valid for the entire project, and the macro definition name remains valid in the source file unless you encounter a redefinition in the source file or you specify the name of the macro definition with the #undef.

3. Conditional compilation Instructions
In general, at compile time for each line in the source program to compile, but sometimes you want a part of the program only to meet certain conditions to compile, if not meet this condition, do not compile this part of the content, which is conditional compilation. Conditional compilation is primarily a selective selection at compile time, commenting out some of the specified code to achieve multiple versioning and prevent duplicate file inclusion. #if, #ifndef, #ifdef, #else, #elif, #endif是比较常见条件编译预处理指令, you can determine a compilation condition based on the value of an expression or whether a particular macro is defined.
① directive meaning
The code is compiled #if the expression is nonzero;
#ifdef Compile if the macro is defined;
#ifndef Compile if the macro is not defined;
#else compiled as the remaining option for other preprocessing;
#elif This is a combination of #else and # if options;
#endif end the control of the compilation block.
② Common Forms
#if_ #endif form:
#if constant expression or #ifdef macro name or #ifndef macro name
Program Segment
#endif
If the constant expression is true or the macro name is defined or the macro name is undefined, the subsequent program segment is compiled, otherwise it will not compile and skip the program.
#if_ #else_#endif form:
#if constant expression or #ifdef macro name or #ifndef macro name
Procedure Section 1
#else
Procedure Section 2
#endif
If the constant expression is true or the macro name is defined or the macro name is undefined, the subsequent program segment 1 is compiled, or the subsequent program segment 2 is compiled.
#if_ #elif_#endif form:
#if constant Expression 1
Procedure Section 1
#elif constant Expression 2
Procedure Section 2
.......
#elif constant-expression n
Program Segment N
       #endif
Span style= "COLOR: #ff0000" >       Note that this form #elif can not be used in #ifdef and #ifndef, but #else can.
      ③ expression
Span style= "Font-family:microsoft Yahei; font-size:18px ">       preprocessor expressions include operators that mainly involve the operation of a single number (+ 、-、 ~, <<, >>), Multiple operations (* ,/,%, + 、-、 &, ^, |), relationship comparison (<, <=, >, >=, = =,! =), macro definition judgment (defined), logical operation (!, &&, | | ), with the same precedence and behavior as the C + + expression operator. for preprocessor expressions, it is important to remember that they are executed on the compiler preprocessor and before compilation.
       The following table lists the order of precedence of the operators, from top to bottom, from highest to lowest. You can change the order of precedence with parentheses.

Example: #ifndef has the same meaning as # if!defined, #ifdef has the same meaning as # if defined.

4. Other pre-processing instructions
In addition to the common preprocessing directives discussed above, there are three less common preprocessor directives: #line, #error, #pragma, respectively.
① #line
#line指令用于重新设定当前由__FILE__和__LINE__宏指定的源文件名字和行号.
#line一般形式为 #line number "filename", where the line numbers are any positive integers, the file name filename is optional. #line主要用于调试及其它特殊应用,Note the number of line numbers specified after #line is the line number that represents the beginning of the next line.
② #error
#error指令使预处理器发出一条错误消息, and then stop performing the preprocessing.
#error general form is #error info, such as #error MFC requires C + + compilation.
③ #pragma
#pragma指令可能是最复杂的预处理指令, its role is to set the state of the compiler or instruct the compiler to complete some specific actions.
#pragma一般形式为 #pragma para, where para is the parameter, some commonly used parameters are described below.
#pragma once, you can ensure that header files are compiled once by adding this instruction at the very beginning of the header file.
#pragma message ("info"), output the appropriate information in the Compile Information Output window, such as #pragma message ("Hello").
#pragma warning, sets how the compiler handles compilation warning messages, such as #pragma warning (disable:4507 34;once:4385;error:164) equivalent to #pragma warning (disable : 4507 34) (does not display 4507 and 34th warning messages), #pragma warning (once:4385) (No. 4385 warning information is reported only once), #pragma warning (error:164) (164th warning message as an error).
#pragma comment (...), set a comment to be recorded in the object file or in the executable file. A common Lib annotation type used to link a library file to a target file, generally in the form of #pragma comment (lib, "*.lib"), with the same effect as the input file in the Project Property linker "Additional dependencies."

"Reprint" C/C + + preprocessor

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.