#ifndef ( if not defined ) directive is used in C language for conditional execution of certain section of code.
Firs, we demonstrate when it is required to use the #ifndef .
1) lets create a minimum header file which we are going to include in the C program.
$ vim ifndef_endif.h
save and close this ifndef_endif.h
int a = 10;
2) Now, we will write simple C program as below,
$ vim ifdef_example.c
#include <stdio.h>
#include "ifndef_endif.h"
int main(void) {
printf("%d\n", a);
return 0;
}
If we compile this program, it would easily get compiled without any error as below,
$ gcc -o ifdef_example ifdef_example.c
$ ./ifdef_example
10
3) Our above program was verify simple, now what if there is a program of thousands of line, with hurndreds of headers included. In that case, there are higher chances we will make a mistake like adding the same header at more places like as below,
#include <stdio.h>
#include "ifndef_endif.h"
#include "ifndef_endif.h"
int main(void) {
printf("%d\n", a);
return 0;
}
So this new C file has tried to include ifndef_endif.h twice, which can happen when we are writing large amount of code in practical.
now lets try to compile this c code and see what it shows.
$ gcc -o ifdef_example ifdef_example.c
In file included from ifdef_example.c:3:
ifndef_endif.h:1:5: error: redefinition of ‘a’
1 | int a = 10;
| ^
In file included from ifdef_example.c:2:
ifndef_endif.h:1:5: note: previous definition of ‘a’ with type ‘int’
1 | int a = 10;
| ^
As we can see above, this program didn’t got compiled.
Reason: because in our headers, “ifndef_endif.h” we had defined “int a = 10” and then by mistake we added this header twice into our program.
Solution :
So, how to avoid this error and even if added header multiple times, our code should add this header only once and ignore the multiple additions.
This is where, #ifndef directive comes to our help.
Now, what we need to do is, just use the #ifndef macro in header and rewrite header as,
#ifndef __IFNDEF_ENDIF_H
#define __IFNDEF_ENDIF_H
int a = 10;
#endif
Now, if we compile the C program, it will get compiled without any error as,
$ gcc -o ifdef_example ifdef_example.c
$ ./ifdef_example
10
So, how this worked ????
Because we used #ifndef to check whether our macro __IFNDEF_ENDIF_H is not defined, if it is not defined , define the macro once using “define __IFNDEF_ENDIF_H” … so now even if we added this header multiple times, macro will be checked for first time, as it is not defined first time, if will define macro and for any next time, “ifndef” will turn false and header contains will not get added.