<<Navigation: 执行失败 ['AllContext' object has no attribute 'values'] (see also the log)>>

4.11.3 Conditional Inclusion 条件包含

It is possible to control preprocessing itself with conditional statements that are evaluated during preprocessing. This provides a way to include code selectively, depending on the value of conditions evaluated during compilation.

还可以使用条件语句对预处理本身进行控制,这种条件语句的值是在预处理执行的过程中进行计算。这种方式为在编译过程中根据计算所得的条件值选择性地包含不同代码提供了一种手段。

The #if line evaluates a constant integer expression (which may not include sizeof, casts, or enum constants). If the expression is non-zero, subsequent lines until an #endif or #elif or #else are included. (The preprocessor statement #elif is like else-if.) The expression defined(name) in a #if is 1 if the name has been defined, and 0 otherwise.

#if语句对其中的常量整型表达式(其中不能包含sizeof、类型转换运算符或enum常量)进行求值,若该表达式的值不等于0,则包含其后的各行,直到遇到#endif、#elif或#else语句为止(预处理器语句#elif类似于else if)。在#if语句中可以使用表达式defined(名字),该表达式的值遵循下列规则:当名字已经定义时,其值为1;否则,其值为0。

For example, to make sure that the contents of a file hdr.h are included only once, the contents of the file are surrounded with a conditional like this:

   #if !defined(HDR)
   #define HDR

   /* contents of hdr.h go here */

   #endif

The first inclusion of hdr.h defines the name HDR; subsequent inclusions will find the name defined and skip down to the #endif. A similar style can be used to avoid including files multiple times. If this style is used consistently, then each header can itself include any other headers on which it depends, without the user of the header having to deal with the interdependence.

例如,为了保证hdr.h文件的内容只被包含一次,可以将该文件的内容包含在下列形式的条件语句中:

   #if !defined(HDR)
   #define HDR

   /* contents of hdr.h go here */

   #endif

第一次包含头文件hdr.h时,将定义名字HDR;此后再次包含该头文件时,会发现该名字已经定义,这样将直接跳转到#endif处。类似的方式也可以用来避免多次重复包含同一文件。如果多个头文件能够一致地使用这种方式,那么,每个头文件都可以将它所依赖的任何头文件包含进来,用户不必考虑和处理头文件之间的各种依赖关系。

This sequence tests the name SYSTEM to decide which version of a header to include:

   #if SYSTEM == SYSV
       #define HDR "sysv.h"
   #elif SYSTEM == BSD
       #define HDR "bsd.h"
   #elif SYSTEM == MSDOS
       #define HDR "msdos.h"
   #else
       #define HDR "default.h"
   #endif
   #include HDR

下面的这段预处理代码首先测试系统变量SYSTEM,然后根据该变量的值确定包含哪个版本的头文件:

   #if SYSTEM == SYSV
       #define HDR "sysv.h"
   #elif SYSTEM == BSD
       #define HDR "bsd.h"
   #elif SYSTEM == MSDOS
       #define HDR "msdos.h"
   #else
       #define HDR "default.h"
   #endif
   #include HDR

The #ifdef and #ifndef lines are specialized forms that test whether a name is defined. The first example of #if above could have been written

   #ifndef HDR
   #define HDR

   /* contents of hdr.h go here */

   #endif

C语言专门定义了两个预处理语句#ifdef与#ifndef,它们用来测试某个名字是否已经定义。上面有关#if的第一个例子可以改写为下列形式:

   #ifndef HDR
   #define HDR

   /* contents of hdr.h go here */

   #endif

TCPL/4.11.3_Conditional_Inclusion (2008-02-23 15:35:00由localhost编辑)

ch3n2k.com | Copyright (c) 2004-2020 czk.