Pages

Monday, December 20, 2010

Macros - Conditional Compilation

Another use of macros is to use them for conditional compilation. By "conditional compilation", we mean that if certain portions of a program are to compiled only if a particular condition is met we can use these macros. Conditional compilation can be done using "ifdef" and "ifndef" macros,which mean ''if defined" and "if not defined," respectively. The working of #ifdef - #else - #endif is similar to the ordinary if - else statements.
The general form of #ifdef is
#ifdef macroname
statements
#endif

If macro-name has been previously defined in a #define statement, the block of code will be compiled.

Syntax
#ifndef macroname
statements
#endif



If macro-name is currently undefined by a #define statement, the block of code is compiled. Both #ifdef and #ifndef may use an #else or #elif statement.

For example

#include
#define DATA 100
void main()
{
#ifdef DATA
printf("DEFINED");
#else
printf("NOT DEFINED");
#endif
#ifndef VALUE
printf("VALUE is not defined\n");
#endif
}

The above program will print "DEFINED", since the macro DATA is defined. The message "VALUE is not defined" will also get printed since there is no macro defined by the name VALUE.

Such a technique is mainly used by the programmers to make their program work over different platforms. Using the "ifdef" macro we can write different codes for different type of platforms. For example, to process different type of codes for different type of OS we can write a code as
{
#ifdef WINDOWS7
write statement for Windows 7
#else
write statement for  Windows XP
#endif
}


The above code will check if a macro named WINDOWS7 is defined, if yes, it will process the statements written for Windows 7 otherwise will move to the next statement.

#if and #elif Directives
In addition to #ifdef, there is a another method to check whether a macro name is defined. We can
use the #if directive  with the defined compile-time operator.
Syntax
defined macroname

If macro name is defined, the expression will result in true, otherwise false.

Example
#if defined DATA
or
#ifdef DATA


The above 2 statements will check if the macro named "DATA" is defined or not.


#undef
The #undef directive undefines a previously defined macro definition.

Syntax
#undef macroname

For example:
#define HOUR 24
printf("\nThere are %d hours in a day",HOUR);
#undef HOUR

The above code first defines a macro named HOUR with a value of 24. The value is printed and then undefined using the #undef directive. After a macro is undefined you can not use it in the program. Although it is rarely used, we should have the knowledge about how to "undefine" a macro also.

0 comments:

Post a Comment