C # Preprocessor Directives

Source: Internet
Author: User

There are many commands called preprocessing directives in C # that never translate to commands in executable code, but affect all aspects of the compilation process. For example, you can use preprocessor directives to prevent a compiler from compiling a portion of your code. You can use these preprocessor directives if you plan to release two versions of Code, that is, the base version and the Enterprise version with more features. When compiling a basic version of the software, use preprocessor directives to prevent the compiler from compiling code that is related to additional functionality. In addition, you can also use preprocessor directives when writing code that provides debugging information. In fact, when selling software, you generally do not want to compile this part of the code.

Pre-processing directives have a sign # at the beginning.

1. #define和 #undef

#define的用法如下所示:

#define DEBUG

It tells the compiler that there is a symbol for the given name, in this case Debug. This is a bit like declaring a variable, but the variable does not have a real value, it just exists. This symbol is not part of the actual code, but exists only when the compiler compiles the code. It doesn't make any sense in C # code.

#undef正好相反, it deletes the definition of the symbol:

#undef DEBUG

If the symbol does not exist, #undef就没有任何作用. Similarly, a # define does not work if the symbol already exists. You must place the # define and #undef commands at the beginning of the C # source file before you declare the code for any objects that you want to compile. #define本身没有什么用, it is very powerful when used in conjunction with other preprocessor directives, especially if # if.

  

2. #if/#elif/#elese/#endif

This instruction tells the compiler whether to compile a block of code. Consider the following method:

int Dosomework (double  x) {    //dosomething    #if DEBUG         Console.WriteLine (""+x);     #endif }

This code compiles as usual, but the Console.WriteLine command is contained within the # if clause. This line of code executes only after the symbol debug has been defined in the previous # define command. When the compiler encounters an # if statement, it first checks to see if the relevant symbol exists and compiles the code in the # if clause if the symbol exists. Otherwise, the compiler ignores all code until a matching #endif instruction is encountered. In general, you define symbol debug at debug time and put debugging-related code in the # if clause. After debugging is completed, the # define statement is commented out, all the debugging code will magically disappear, the executable will be smaller, the final use will not be confused by these debugging information. This technique is common in C and C + +, called conditional compilation.

The #elif (=else if) and #else directives can be used in the # if block, meaning it is very intuitive. You can also nest # if blocks:

#defineENTERPRISE#defineW2k//further on the file#ifENTERPRISE//So something    #ifW2k//some code that's only relevant to enterprise//Edition running on W2K    #endif#elifPROFESSIONAL//Do something else    #else        //code for the leaner version    #endif

#if和 #elif also supports a set of logical operators "!" /"= ="/"! ="/"| | |". If the symbol exists, it is considered true, otherwise false, for example:

#if W2K  &&  (enterprise==false)   //if W2K is defined but ENTERPRISE isn ' t

Example//Preprocessor_if.cs #defineDEBUG#defineVc_v7usingSystem; Public classMyClass {Static voidMain () {#if(DEBUG &&!) VC_V7)Console.WriteLine ("DEBUG is defined"); #elif(! DEBUG && vc_v7)Console.WriteLine ("vc_v7 is defined"); #elif(DEBUG && vc_v7)Console.WriteLine ("DEBUG and vc_v7 are defined"); #elseConsole.WriteLine ("DEBUG and Vc_v7 is not defined"); #endif}} output Debug and vc_v7 is defined

3. #warning和 #error

Another two very useful preprocessor directives are #warning and #error, which generate a warning or an error, respectively, when the compiler encounters them. If the compiler encounters a #warning instruction, the text after the #warning instruction is displayed to the user, and the compilation proceeds. If the compiler encounters the #error instruction, it will display the following text to the user as a compile error message, and then immediately exit the compilation without generating Il code.

Using these two instructions to check if a # define statement is doing something wrong, use the #warning statement to review what you have done:

#if Dubug && release    #error "You ' ve defined DEBUG and release simultaneously! "#endif#warning " Don t forget to remove this line before the boss tests the code! "     Console.WriteLine ("*i Hate this job*");

4. #line

#line指令可以用于改变编译器在警告和错误信息中显示的文件名和行号信息. This instruction is not used very much. If you are writing code, you can use this directive to change the input code with some packages before sending it to the compiler, because this means that the line number or file name that the compiler reports does not match the line number or the edited filename in the file. #line指令可以用于还原这种匹配. You can also use the syntax #line default to revert the line number to the line number:

164 " Core.cs "            // we happen to know                                This was line 164 in the file // Core.cs, before the intermediate                                 // Package mangles it. // later on #line Default                  //  restores default line numbering        

5. #pragma

#pragma指令可以抑制或者还原指定的编译警告. Unlike command-line options, #pragma指令可以在类或方法级别执行, finer control over the content of suppressed warnings and the time to suppress them. The following example disables the "field not used" warning, and then restores the warning after compiling the MyClass class.

#pragma warning Disable 169class  myclass{       int  Neverusedfield;      }  #pragma warning Restore 169

C # Preprocessor Directives

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.