#ifdef directive in C


Reading time: 20 minutes | Coding time: 5 minutes

ifdef is a include guard. It is a define directive in C which checks if a MACRO has been defined previously or not. If it has been defined, it will define more MACROs and other statements. It is used for conditional compilation.

ifndef can be seen as "if defined" then do this till endif. It is opposite of ifndef directive

Syntax:

#ifdef <macro_definition>
... some code statements
#endif

The real use is in defining behaviour according to a given parameter. For example, for Windows operating system, we need certain macros and behaviour and for other operating systems, it should be different.

Example

Consider that we have a header file named windows.h as follows:

#define WIN_VERSION "95"

We shall have another header file for Linux named ubuntu.h as follows:

#define UBUNTU_VERSION "1.16"

We will have a client header code named os.h which will import either of the two header files as follows:

import windows.h

Now in our client code os.c, we will do checks like:

#include <stdio.h>
#include "os.h"

#ifdef WIN_VERSION
#define os_code 1
#endif

#ifdef UBUNTU_VERSION
#define os_code 2
#endif

int main()
{
    printf("%d", os_code);
    return 0;
}

Output:

1

We will take a look at another example (an extension of the above example) to understand that ifdef can be used within the code as well to define different code segments as per the defined macros.

#include <stdio.h>
#include "os.h"

int main()
{
    #ifdef WIN_VERSION
    printf("You have a windows computer");
    #endif
    
    #ifdef UBUNTU_VERSION
    printf("You have an Ubuntu computer");
    #endif
    return 0;
}

Output:

You have a windows computer

Applications

In production level, this is greatly used to define compile time behaviour. Software and hardware environments will have different macros defined in their header files and depending upon that we can activate different code segments.

We can use if else statements in this case but using ifdef is advantageous in terms of performance as the code segment that will not be executed will be removed from the executable and hence, there is no runtime condition checking which will allow better system utilization.

Hence, use ifdef instead of if else whenever possible.