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

Source: Internet
Author: User

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 with # define
    #include <stdio.h>#defineMAX (x, Y) ((() > (y))? ( x):(y))#defineMIN (x, Y) ((() < (y))? ( x):(y))intMainvoid) {#ifdef MAX//Determine if the macro is definedprintf"3 and 5 the max is:%d\n", MAX (3,5));#endif#ifdef MIN printf ("3 and 5 the min is:%d\n", MIN (3,5));#endif    return 0;}/** (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 the macro is simply a text replacement, not pay attention, easy to cause ambiguity error. */
  2. Incorrect use of macro definitions
    #include <stdio.h>#defineSQR (x) (x*x)intMainvoid){    intb=3; #ifdef SQR//only need the macro name on it, no parameters, parameters will be warnedprintf"A =%d\n", SQR (b +2));#endif    return 0;}/** First of all, the definition of this macro is wrong. Does not implement the b+2 of the program in the time of the square * preprocessing, replaced by the following results: B+2*b+2 * The correct macro definition should be: #define SQR (x) ((x) * (x)) * So, try to use parentheses, enclose the argument. */
  3. connection to Macro parameters
    #include <stdio.h>#defineSTR (s) #s#defineCONS (A, b) (int) (a# #e # #b)intMainvoid{#ifdef str printf (str (VCK));#endif#ifdef CONS printf ("\n%d\n", CONS (2,3));#endif    return 0;}/*(The vast majority of these are not used, the use of the word, see the manual can be) * The first macro, using # to convert parameters into a string * the second macro, with # #把2个宏参数粘合在一起, and Aeb,2e3 is the*/
  4. Use a macro to get a high or low byte of a word
    #include <stdio.h>#define word_lo (XXX) ((byte) ((WORD) (XXX) & 255)#define word_hi (XXX) ( byte) ((word) (XXX) >> 8))int main (void) {    return0;} /* * One word 2 bytes, get low byte (low 8 bit), with 255 (0000,0000,1111,1111) bitwise phase and * Get high byte (high 8 bit), shift right 8 bit. */
  5. Define a macro to get the number of elements in an array
     #include <stdio.h>  #define  Arr_size (a) (sizeof ((a))/sizeof ((a[0))) int  Main ( void   int  array[ 100    array has%d items.\n   " ,arr_size (Array) );     #endif  return  0  ;}  /*   * 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:
    #include <stdio.h>#include<stdlib.h>#defineDEBUGintMainvoid){    inti =0; CharC;  while(1) {i++; C=GetChar (); if('\ n'!=c) {GetChar (); }        if('Q'= = C | |'Q'==c) {#ifdef DEBUG//determine if debug has been definedprintf"We get:%c,about to exit.\n", c);#endif             Break; }        Else{printf ("i =%d", i); #ifdef DEBUG printf (", we get:%c", c);#endifprintf ("\ n"); }} printf ("Hello world!\n"); return 0;}/*#endif用于终止 # if preprocessing directives. */
  2. Ifdef and #ifndef
    #include <stdio.h>#define DebugMain () {#ifdef debug    printf ("" ); #endif #ifndef DEBUG    printf (""); #endif }//#ifdefined等价于 #ifdef; // #if!defined equivalent to #ifndef
  3. #else指令

  4. #elif指令

  5. Some other directives
    #error指令将使编译器显示一条错误信息, and then stop compiling. #line指令可以改变编译器用来指出警告和错误信息的文件号和行号. #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.

Reference: The Shadow of the Night

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

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.