Conditional Compilation in C

C provides a very useful and interesting feature called “conditional Compilation

the general structure for doing it:

#ifdef macroname

statement 1;
statement 2;
statement 3;
statement 4;
#endif

here if macroname has been #defined then the 4 statements will be compiled otherwise not.

There are 3 scenarios where I see application of this feature:

-> To “comment out” obselete lines of code. It may happen that a program undergoes a change for some reasons.
Here we may not want to delete the old code but add new code.
In this scenario, we can include the old and new code in ifdef block and control the compilation using a single #define statement.

eg:

void main()
{

#ifdef OLD
statement 1;
statement 2;
#else
statement 3;
statement 4;

#endif

}

here , if we define thee macro “OLD” then old code is compiled otherwise, the new code is compiled.

->The other (more sophisticated) use of this feature can be to make the programs more portable.
Thus, we can make use of this feature and make a program work on two completely different computers.

eg:

void main()
{
#ifdef INTEL
code for intel PC
#else
code for motorola PC
#endif
code common for both.

}

This code is pretty self explanatory.
If you want your code to run on INTEL we just need to define a macro.

->A third possible scenario is defining of custom functions.
Lets say we define a function called “my_sample_function()” in a file “file1.h”
Also, “file1.h” is included in “file2.h

If we include both the files, compiler will throw an error saying “multiple declaration of my_sample_function()

To overcome this problem, we can use the following way:

/* file1.h */

#ifndef _file
#define _file
my_sample_function()
{
/*some code */
}
#endif

Here when file1.h gets included first time, compiler knows that macro _file is not defined. Thus it gets defined and the rest of code is compiled.
Next time, since the macro stands defines, the function does not get compiled and thus there is no error.

NOTE: #ifndef is exactly opposite of #ifdef

 

Conditional compilation can also be achieved using #if ,#else #endif statements.

#if is used to evaluate whether a expression evaluated to nonzero value or not.

it is used in the same way as above:

eg:

 

void main(){

if TEST<=5

statment 1;

#else

statement 2;

#endif

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s