ifdef and ifndef

mainIf you have worked on a large code base before, you would have seen ifdef and ifndef statements a lot of times. In fact, it is a good practice to have them wherever necessary. It just adds more robustness to your code and if you are working in a team, it helps you avoid weird compiler issues. The preprocessor directive #ifdef is used to define conditional groups of code at the preprocessor level. Based on a condition, a piece of code may or may not be included in the program. The body of this directive is usually termed controlled text.  

#ifdef MY_MACRO
//some code
#endif

In the above example, the body of #ifdef is included only if MY_MACRO is defined. As we all know, the #define directive is used to define macros.

Here’s a sample program.

#ifdef MY_MACRO
void myFunction()
{
}
#endif

int main()
{
    return 1;
}

Observe that MY_MACRO is not defined. Hence, the controlled text should not be included. Here’s the output of the preprocessor is (compiled with -E option):

# 1 "mycode.c"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "mycode.c"

int main()
{
    return 0;
}

The numbers in the third line i.e “1 3 4” are just flags. We will discuss them some other time. Let’s now define the macro #ifdef using #define.

#define MY_MACRO

#ifdef MY_MACRO
void myFunction()
{
}
#endif

int main()
{
    return 1;
}

And this is the output of the preprocessor now.

# 1 "mycode.c"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "mycode.c"

void myFunction()
{
}

int main()
{
    return 0;
}

You can observe that when the macro is defined, the controlled text is included. Note again that the preprocessor does not know whether the controlled text is a function or any of the C constructs. All it sees is some text. You can also define macros when invoking the compiler with the -D option. Compiling the code as gcc -E -DMY_MACRO mycode.c gives you the same output.

————————————————————————————————-

3 thoughts on “ifdef and ifndef

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s