C + + preprocessing directive # define, #ifdef, #ifndef, #endif ...

Source: Internet
Author: User

This article has been transferred from the post-C + + preprocessor directive # define, #ifdef, #ifndef, #endif .... This blog post is particularly well written, especially reproduced.

In this paper, we mainly record the pre-C + + preprocessor directives, and the common preprocessing directives are:

    1. #空指令, without any effect
    2. #include包含一个源代码文件
    3. #define定义宏
    4. #undef取消已定义的宏
    5. #if如果给定条件为真, the following code is compiled
    6. #ifdef如果宏已经定义, the following code is compiled
    7. #ifndef如果宏没有定义, the following code is compiled
    8. #elif如果前面的 # If the given condition is not true and the current condition is true, compile the following code
    9. #endif结束一个 # If ... #else条件编译块
    10. #error停止编译并显示错误信息

Originally just want to know about #ifdef, #ifndef, #endif的, did not expect to find so many pre-processing instructions, most of the above are common, but usually do not pay attention to the content of pre-treatment, so here to comb the knowledge bar. At the same time there is something wrong, or missing what content, also please leave a message to point out.

What is a preprocessing directive?

A preprocessing directive is a line of code that begins with a # number. #号必须是该行除了任何空白字符外的第一个字符. #后是指令关键字, there are any number of whitespace characters allowed between the keyword and the # number. The entire line of statements forms a preprocessing directive that makes certain transformations to the source code before the compiler compiles it.

Scholars who have not cared about before have noticed that the preprocessing directives are the operations that are performed before the compiler compiles the compiler. The preprocessing process scans the source code, makes a preliminary conversion, and generates a new source code to provide to the compiler. The preprocessing process can be seen before the source code is processed by the compiler. In many programming languages, there is no intrinsic mechanism to do the following: include other source files at compile time, define macros, and, depending on the criteria, determine whether to include some code at compile time (to prevent duplicates from including certain files). To do this, you need to use a preprocessor. Although the majority of compilers now contain preprocessor, they are generally considered to be independent of the compiler. The preprocessing process reads the source code, examines the statements and macro definitions that contain the preprocessing directives, and transforms the source code into a response. The preprocessing process also removes comments and extra white-space characters from the program.

#include包含一个源代码文件

This preprocessing directive, I think is the most seen one, briefly speaking, the first method is to use angle brackets to the head file. This format tells the preprocessor to search for included header files in the header files of the compiler's own or external libraries. The second method is to enclose the file in double quotation marks. This format tells the preprocessor to search for the included header file in the source code file of the currently compiled application, and then search the compiler's own header file if it is not found. The rationale for using two different include formats is that the compiler is installed in a common subdirectory, and the compiled application is under their own private subdirectory. An application contains both the common header file provided by the compiler and the custom private header file. Two different inclusion formats allow the compiler to differentiate a common set of header files in many header files.

#define定义宏

For the macro definition of # define, there are a lot of uses in C, because # define has some shortcomings, and C + + emphasizes using const to define constants. A macro defines an identifier that represents a specific content. The preprocessing process replaces the macro identifier that appears in the source code with the value of the macro definition. Remember to just replace the identifier. Here are some examples of the use of # define:

1. Macro for maximum and minimum values in # define
1#include <stdio.h>2 #defineMAX (x, Y) ((() > (y))? ( x):(y))3 #defineMIN (x, Y) ((() < (y))? ( x):(y))4 intMainvoid)5 {6#ifdef MAX//Determine if the macro is defined7printf"3 and 5 the max is:%d\n", MAX (3,5));8 #endif9 #ifdef MINTenprintf"3 and 5 the min is:%d\n", MIN (3,5)); One #endif A     return 0; - } -  the /* - * (1) Ternary operators are more efficient than If,else - * (2) The use of macros must be careful, you need to carefully enclose the parameters in parentheses, - * Because macros are simply text replacements, not paying attention, it is easy to cause ambiguity errors.  + */
2. Incorrect use of macro definitions
1#include <stdio.h>2 #defineSQR (x) (x*x)3 intMainvoid)4 {5     intb=3;6#ifdef SQR//only need the macro name on it, no parameters, parameters will be warned7printf"A =%d\n", SQR (b +2));8 #endif9     return 0;Ten } One  A /* - * First of all, the definition of this macro is wrong. Does not implement the b+2 of the program in the square - * When preprocessing, replace with the following result: B+2*b+2 the * The correct macro definition should be: #define SQR (x) ((x) * ( x)) - * Therefore, use parentheses as much as possible to enclose the parameters.  - */
3. Connection of macro parameters
1#include <stdio.h>2 #defineSTR (s) #s3 #defineCONS (A, b) (int) (a# #e # #b)4 intMainvoid)5 {6 #ifdef STR7 printf (STR (VCK));8 #endif9 #ifdef CONSTenprintf"\n%d\n", CONS (2,3)); One #endif A     return 0; - } -  the /*(The vast majority of these are not used, if used, the manual can be viewed) - * First macro, using # to convert parameters into a string - * Second macro, with # #把2个宏参数粘合在一起, and Aeb,2e3 - */
4. Use a macro to get a high or low byte of a word
1#include <stdio.h>2 #defineWord_lo (XXX) ((byte) ((word) (XXX) & 255))3 #defineWord_hi (XXX) ((byte) ((word) (XXX) >> 8))4 intMainvoid)5 {6     return 0;7 }8 9 /*Ten * One word 2 bytes, get low byte (low 8 bit), with 255 (0000,0000,1111,1111) by phase with One * Get high-byte (high 8-bit) and move right 8-bit.  A */
5. Define the number of elements contained in an array with a macro
1#include <stdio.h>2 #defineArr_size (a) (sizeof ((a))/sizeof ((a[0)))3 intMainvoid)4 {5     intarray[ -];6 #ifdef arr_size7printf"Array has%d items.\n", Arr_size (array));8 #endif9     return 0;Ten } One /* A * Total size divided by size of each type -  */

With regard to the use of the # define macro, special care should be taken, especially when it comes to parameter calculations such as the small 2 example, and the most insured approach is to enclose the parameters in parentheses.

#ifdef, #ifndef, #endif ... The use

These pre-compilation directives are conditional compilation directives, that is, will determine which code is compiled and which is not.

1. Example 1
1#include <stdio.h>2#include <stdlib.h>3 #defineDEBUG4 intMainvoid)5 {6     inti =0;7     CharC;8      while(1)9     {Teni++; Onec =GetChar (); A         if('\ n'!=c) -         { - GetChar (); the         } -         if('Q'= = C | |'Q'==c) -         { -#ifdef DEBUG//determine if debug has been defined +printf"We get:%c,about to exit.\n", c); - #endif +              Break; A         } at         Else -         { -printf"i =%d", i); - #ifdef DEBUG -printf", we get:%c", c); - #endif inprintf"\ n"); -         } to     } +printf"Hello world!\n"); -     return 0; the } *  $ /*#endif用于终止 # if preprocessing directives. */
2. Ifdef and #ifndef
1#include <stdio.h>2 #defineDEBUG3 Main ()4 {5 #ifdef DEBUG6printf"Yes");7 #endif8 #ifndef DEBUG9printf"No");Ten #endif One } A //#ifdefined等价于 #ifdef; - //#if!defined equivalent to #ifndef
3. #else指令

  

4. #elif指令

  

5. Some other directives
1 #error指令将使编译器显示一条错误信息, and then stop compiling.  2#line指令可以改变编译器用来指出警告和错误信息的文件号和行号.  3 #pragma指令没有正式的定义. The compiler can customize its purpose. A typical use is to prohibit or allow some annoying warning messages.

Summary:

Preprocessing is the work done prior to the first lexical scan and parsing of the compilation. To be blunt, the preprocessing part is processed before the source file is compiled, and then the processed code is compiled. The advantage of this is that the processed code will become very short.

C + + preprocessing directive # define, #ifdef, #ifndef, #endif ... Go

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.