9.3 Conditional Compilation

[This section corresponds to Sec. 4.11.3]

The last preprocessor directive we're going to look at is ifdef. If you have the sequence ifdef name program text else more program text endif in your program, the code that gets compiled depends on whether a preprocessor macro by that name is defined or not. If it is (that is, if there has been a define line for a macro called name), then ``program text'' is compiled and ``more program text'' is ignored. If the macro is not defined, ``more program text'' is compiled and ``program text'' is ignored. This looks a lot like an if statement, but it behaves completely differently: an if statement controls which statements of your program are executed at run time, but ifdef controls which parts of your program actually get compiled.

Just as for the if statement, the else in an ifdef is optional. There is a companion directive ifndef, which compiles code if the macro is not defined (although the ``else clause'' of an ifndef directive will then be compiled if the macro is defined). There is also an if directive which compiles code depending on whether a compile-time expression is true or false. (The expressions which are allowed in an if directive are somewhat restricted, however, so we won't talk much about if here.)

Conditional compilation is useful in two general classes of situations:

Conditional compilation can be very handy, but it can also get out of hand. When large chunks of the program are completely different depending on, say, what operating system the program is being compiled for, it's often better to place the different versions in separate source files, and then only use one of the files (corresponding to one of the versions) to build the program on any given system. Also, if you are using an ANSI Standard compiler and you are writing ANSI-compatible code, you usually won't need so much conditional compilation, because the Standard specifies exactly how the compiler must do certain things, and exactly which library functions it much provide, so you don't have to work so hard to accommodate the old variations among compilers and libraries.


Bhopal news
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

freelance web designer india ecommerce web developer | Ecommerce web design, software developer india | Web hosting India Windows hosting | India web hosting Windows hosting India | India software developer | web designer india