PERENNIAL FASCINATION WITH ALL THINGS TECH

Main menu

Post navigation

ifdef and ifndef

If 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):

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.