Tips for using _ ifdef and _ elseif in C

Source: Internet
Author: User

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

# Denif

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.

 

 

# Advantages of ifdef in software development

 

I am engaged in the development and maintenance of an application software in a UNIX environment. Users are distributed all over the country and the basic functions required by all users are the same. However, some functions need to change as demand changes, it is difficult to upgrade users throughout the country, but we only use E-mail to send patches to users, these patches are constantly modified and expanded based on a set of software, and are transferred from different logo files to different modules. Although the program volume is constantly expanding, however, it does not affect the functions of old users at all. This is mainly due to the role of # ifdef/# else/# endif in the C program.

 

 

We mainly use the following methods. Assume that we have defined # ifdef DEBUG and # ifdef TEST in the program header:

 

1. Use # ifdef/# endif to include a program function module to provide this function to a user.

 

Define # ifdef HNLD in the program header:

 

# Ifdef HNLD

 

Include "n166_hn.c"

 

# Endif

 

If you are not allowed to provide this function to other users, add an underscore to the native ld of the header before compilation.

 

2. Add a flag before each subroutine to track the running of the program.

 

# Ifdef DEBUG

 

Printf ("Now is in hunan! ");

 

# Endif

 

3. Avoid hardware restrictions. Sometimes the hardware in some specific application environments is different, but due to restrictions, the local device lacks such a device, so the hardware is bypassed and the expected results are directly written. The specific method is:

 

# Ifndef TEST

 

I = dial ();

 

// This statement is bypassed during program debugging and running.

 

# Else

 

I = 0;

 

# Endif

 

After the debugging is passed, shield the definition of TEST and re-compile it, and then send it to the user.

 

# Ifdef # ifndef and other usage (conversion)

 

# Ifndef in the header, which is critical. For example, you have two C files, both of which include the same header file. During compilation, these two C files need to be compiled into a runable file together, so the problem arises and a large number of declarations conflict.

 

Put the header file content in # ifndef and # endif. Whether or not your header file will be referenced by multiple files, you must add this. The general format is as follows:

 

# Ifndef <ID>

# Define <ID>

 

......

......

 

# Endif

 

<Identifier> in theory, it can be freely named, but the "identifier" of each header file should be unique. The naming rule of the identifier is generally that the header file name is in uppercase, followed by an underscore, and the "." In the file name is also changed to an underscore, such as stdio. h.

 

# Ifndef _ STDIO_H _

# Define _ STDIO_H _

 

......

 

# Endif

 

2. Problems with defining variables in # ifndef (generally not defined in # ifndef ).

 

# Ifndef AAA

# Define AAA

...

Int I;

...

# Endif

There is a variable definition in it

When I is linked in vc, an I-defined error occurs, and c is compiled successfully.

 

Conclusion:

 

(1 ). when you first use this header. cpp file generation. in obj, int I defines in it when another one uses this. cpp is generated [separately] again. when obj is used, int I is defined again, and then two obj are another. cpp also includes this header. If the header is connected together, the definition will be repeated.

 

(2). After the source program file extension is changed to. c, VC compiles the source program according to the C language syntax, rather than c ++. In C language, if multiple int I is encountered, one of them is automatically considered to be the definition, and the other is the declaration.

 

(3). the C language and C ++ language have different connection results. It is possible that the C ++ language will

The default value of the variable is a strong symbol, so the connection error occurs. The C language determines the strength based on the initialization. (Reference)

 

Solution:

 

(1). Change the source program file extension to. c.

 

(2). Recommended solutions:

Only extern int I is declared in. h; defined in. cpp

 

<X. h>

# Ifndef _ X_H __

# Define _ X_H __

Extern int I;

# Endif/_ X_H __

<X. c>

Int I;

 

Note:

 

(1). variables are generally not defined in. H files.

 

 

 

This article from the network-China's largest network security site Source: http://www.hackbase.com/tech/2008-05-13/40719.html

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.