C language Conditional compilation instructions

Source: Internet
Author: User

I have learned C language and C ++ for three years, but I still don't know much about Conditional compilation commands. I can see some excellent source code on the Linux platform, such as uC/OS-II used a lot of compilation instructions, MFC also used the Conditional compilation instructions, and now I learned some of the Conditional compilation instructions to make a summary, later, I learned other compilation commands and then added them.

I. prevent duplicate header files from being contained

# Ifndef _ *** _ H

# DEFINE _ *** _ H
Program Section

# Endif

 

This Conditional compilation command is often used in header files to prevent repeated inclusion of header files.

 

 

Ii. # ifdef | # ifndef... # endif Preprocessor Directive (from: http://technet.microsoft.com/zh-cn/library/t22e924w (V = vs.80 ))

Conditionally except des a set of commands at compile time if a compile-time constant is defined.

The format is as follows:

#IFDEF | #IFNDEF ConstantName       Commands[#ELSE       Commands]#ENDIF

 

Parameters
# Ifdef

Specifies that a set of commands is wrongly ded at compile time when
ConstantnameIs defined.

The following items describe how a set of commands is supported at compile time when you include # ifdef:

  • IfConstantnameIs defined, the set of commands following # ifdef and preceding # else or # endif (whichever occurs first) is supported at compile time.

  • IfConstantnameIs not defined and # else is already ded, the set of commands following # else and preceding # endif is already ded at compile time.

  • IfConstantnameIs not defined and # else is not supported ded, no commands within the # ifdef... # endif structure are supported ded at compile time.

# Ifndef

Specifies that a set of commands is wrongly ded at compile time when
ConstantnameIs not defined.

The following items describe how a set of commands is supported at compile time when you include # ifndef:

  • IfConstantnameIs not defined, the set of commands following # ifndef and preceding # else or # endif (whichever occurs first) is supported at compile time.

  • IfConstantnameIs defined and # else is already ded, the set of commands following # else and preceding # endif is already ded at compile time.

  • IfConstantnameIs defined and # else is not supported ded, no commands within the # ifndef... # endif structure are supported ded at compile time.

Constantname

Specifies the compile-time constant whose existence determines whether a set of commands is supported at compile time. compile-time constants are defined with # define.

Commands

Specifies the set of commands that is wrongly ded at compile time.

Remarks

You can nest an # ifdef | # ifndef... # endif structure within another # ifdef | # ifndef... # endif structure.

Comments can be placed on the same line after # ifdef, # ifndef, # else, And # endif. These comments are ignored during compilation and program execution.

 

Examplethe following example creates a compile-time constant named mydefine. # ifdef... # endif displays a message if the compile-time constant has been defined.

DEFINE MYDEFINE 1#IFDEF MYDEFINE      WAIT WINDOW "MYDEFINE exists"#ELSE   WAIT WINDOW "MYDEFINE does not exist"#ENDIF
There is an article on the English digest of the Chinese translation (from the http://hi.baidu.com/urzalknsyzchrur/item/e7deb293889b2649f1421582), as follows: # ifdef | # ifndef... # endif Preprocessor command

During compilation, you can determine whether to compile a piece of code based on whether a compilation constant is defined.

Syntax

# Ifdef | # ifndef constantname
Commands
[# Else
Commands]
# Endif

Parameters
# Ifdef

Specifies that if a compilation constant specified by constantname has been defined, a program code is compiled.
The following describes how to determine the program code to be compiled based on the # ifdef Preprocessor command:

If constantname is defined, compile the program generation from # ifdef to # else or # endif (depending on which one is earlier ).

.
If constantname is not defined, but there is a # else command, the program code between # else and # endif is compiled.
If no constantname is defined and no # else command is available, all programs in the # ifdef... # endif structure are not compiled.
# Ifndef

When no compilation constant specified by constantname is defined, a set of program code to be compiled is specified.
The following describes how to determine the program code to be compiled based on the # ifndef Preprocessor command:

If constantname is not defined, compile the program code between # ifndef and # else or # endif (depending on which one is earlier ).

.
If the constantname has been defined and the # else command is available, compile # Else To # endif
Program code.
If the constantname is defined but there is no # else command, all programs in the # ifndef... # endif structure are not compiled.
Constantname

Specifies the constant used for the compilation time. Its existence determines whether to compile a group of program code. The compilation constant is defined by the # define command.

Commands

Specifies the program code to be compiled.

Description

One # ifdef | # ifndef... # The endif structure can be nested with another # ifdef | # ifndef... # endif
Structure.
Annotations can be placed in # ifdef, # ifndef, # else
And # The End Of The endif row. These annotations are ignored during compilation and program running.

Use this command to replace the C and C ++ annotation functions. The use case is as follows:
#ifdef CODEFuction       :  void sort_Insert(int iArray[], int size);Content      :Parameter  : iArray:int Array                    size   :the length of arrayReturn        : voidDate           :   2012/11/16Description :sort Array of intRemark      :2012/11/16 Append#endif

Or

# Define code 1 # ifndef codefunction: void sort_insert (INT iarray [], int size); content: parameter: iarray int size array number of elements return: nonedate: 2012/11/16 description: insert and sort the array. remark: 2012/11/16 append. # endif
The following text Reprinted from the blog Park newlist of a blog http://www.cnblogs.com/newlist/archive/2012/07/06/2579005.html#ifdef

"# Ifdef Statement 1

 

Procedure 2

 

# Endif"

 

If the macro defines Statement 1, the program 2 can be translated.

 

Purpose: we can use it to separate code related to specific header files, libraries, and other file versions.

 

Code example: Create a define. cpp File

 

# Include "iostream. H"

 

Int main ()

 

{

 

# Ifdef debug

 

Cout <"beginning execution of main ()";

 

# Endif

 

Return 0;

 

}

 

The running result is:

 

Press any key to continue

 

The rewrite code is as follows:

 

# Include "iostream. H"

 

  # Define debug

 

Int main ()

 

{

 

# Ifdef debug

 

Cout <"beginning execution of main ()";

 

# Endif

 

Return 0;

 

}

 

The running result is:

 

Beginning execution of main ()

 

Press any key to continue

 

Generally, the # define statement is contained in a specific header file. For example, create a header file head. h and add code to the file:

 

# Define debug

 

# Ifdef debug

 

# Endif

 

In the define. cpp source file, the code is modified as follows:

 

# Include "iostream. H"

 

  # Include "head. H"

 

  # Define debug

 

Int main ()

 

{

 

# Ifdef debug

 

Cout <"beginning execution of main ()";

 

# Endif

 

Return 0;

 

}

 

The running result is as follows:

 

Beginning execution of main ()

 

Press any key to continue

 

Conclusion:

 

By using the # ifdef indicator, we can separate code related to specific header files, libraries, and other file versions.

 

  Explanation of C language # macros such as ifdef

 

These macros are used for Conditional compilation. Generally, all the rows in the source program are compiled. However, sometimes you want to compile a part of the content only when certain conditions are met, that is, to specify the compilation conditions for a part of the content. This is "Conditional compilation ". Sometimes, you want to compile a group of statements when a condition is met, and compile another group of statements when the condition is not met.

 

The most common form of Conditional compilation commands is:

 

# Ifdef identifier

 

Procedure 1

 

# Else

 

Procedure 2

 

# Endif

 

It is used to compile program segment 1 when the identifier has been defined (generally defined using the # define command). Otherwise, compile program segment 2.

 

The # else part can also be absent, I .e:

 

# Ifdef

 

Procedure 1

 

# Endif

 

The "program segment" can be a statement group or a command line. This Conditional compilation can improve the universality of the C source program. If a C source program runs on different computer systems, there are some differences between different computers. For example, we have a data type. In Windows, we should use the long type, while in other platforms, we should use the float representation. In this case, we often need to make necessary modifications to the source program, this reduces the versatility of the program. You can compile with the following conditions:

 

# Ifdef windows

 

# Define mytype long

 

# Else

 

# Define mytype float

 

# Endif

 

If you compile a program on Windows, you can add

 

# Define windows

 

In this way, compile the following command line:

 

# Define mytype long

 

If the following command line appears before this set of Conditional compilation commands:

 

# Define windows 0

 

After pre-compilation, the mytype in the program is replaced by float. In this way, the source program can be used in different types of computer systems without any modification. Of course, the above is just a simple case. You can design other conditions for compilation based on this idea.

 

For example, when debugging a program, you often want to output some required information, but do not output this information after the debugging is complete. You can insert the following Conditional compilation segments in the source program:

 

# Ifdef debug

 

Print ("device_open (% P) \ n", file );

 

# Endif

 

If you have the following command line before it:

 

# Define debug

 

The value of the file pointer is output when the program is running for debugging and analysis. After debugging, you only need to delete the define command line. Some people may think that Conditional compilation can achieve this goal, that is, adding a batch of printf statements during debugging, and deleting the printf statements one by one after debugging. Indeed, this is acceptable. However, when many printf statements are added during debugging, the modification workload is huge. If you use Conditional compilation, you do not need to delete the printf statement one by one. You only need to delete the previous "# define debug" command, at this time, all the Conditional compilation segments using debug as identifiers make the printf statement ineffective, that is, unified control, just like a "Switch.

 

The following format is also used:

 

# Ifndef identifier

 

Procedure 1

 

# Else

 

Procedure 2

 

# Endif

 

The first line is different from the first form: Change "ifdef" to "ifndef ". It is used to compile program segment 1 if the identifier is not defined; otherwise, compile program segment 2. This form is opposite to the first form.

 

The usage of the above two forms is similar. You can choose one as needed, depending on your convenience.

 

Another form is: # If is followed by an expression instead of a simple identifier:

 

# If expression

 

Procedure 1

 

# Else

 

Procedure 2

 

# Endif

 

It is used to compile program segment 1 when the specified expression value is true (non-zero); otherwise, compile program segment 2. You can specify certain conditions in advance so that the program can execute different functions under different conditions.

 

For example, enter a line of letters, set the condition for compiling as needed, so that all letters can be changed to uppercase for output, or all letters can be changed to lowercase for output.

 

# Define Letter 1

 

Main ()

 

{

 

Char STR [20] = "C Language", C;

 

Int I = 0;

 

While (C = STR [I])! = '\ 0 '){

 

I ++;

 

# If letter

 

If (C> = 'A' & C <= 'Z') C = c-32;

 

# Else

 

If (C> = 'A' & C <= 'Z') C = C + 32;

 

# Endif

 

Printf ("% C", C );

 

}

 

}

 

Running result: C Language

 

Now let's first define letter as 1. In this way, the first if statement is compiled because letter is true (non-zero) in the pre-processing condition compiling command, and the lower-case letters are changed to uppercase when running. If you change the first line of the program:

 

# Define letter 0

 

During preprocessing, the second if statement is compiled to convert uppercase letters into lower-case letters (the ASCII code difference between the upper-case letters and the corresponding lower-case letters is 32 ). The running status is as follows:

 

C Language

 

Some people may ask: what are the advantages of using Conditional compilation commands to directly use if statements without Conditional compilation commands? Indeed, this problem can be solved without the need for Conditional compilation. However, if the target program is long (because all statements are compiled), Conditional compilation can reduce compiled statements, this reduces the length of the target. When there are many Conditional compilation segments, the length of the target program can be greatly reduced.

 
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.