#ifndef in C
In this article, we will explore directive #ifndef in C programming language. We will cover, what #ifndef means, why it’s useful, and how to use it in your code. Whether you’re new to programming or looking to strengthen your understanding, this guide will help you grasp the basics of #ifndef directive in C Programming.
In C programming language, #ifndef is a preprocessor directive that stands for “if not defined”. It is used to create conditional compilation in the code.
The #ifndef directive checks whether a certain symbol has already been defined using the #define directive. If the symbol has not been defined, the code between #ifndef and #endif will be compiled. If the symbol has already been defined, the code will be skipped.
Example of how #ifndef can be used in C code:
#ifndef MY_HEADER_FILE_H
#define MY_HEADER_FILE_H
// code declarations and definitions here
#endif /* MY_HEADER_FILE_H */
In this example, MY_HEADER_FILE_H is the symbol being checked. If it has not been defined with #define, then the code between #ifndef and #endif will be compiled. If it has already been defined, then the code will be skipped.
Using #ifndef is useful when creating header files in C, as it ensures that the header file is only included once in the compilation process.
Here’s an example C program that uses #ifndef to ensure that a header file is only included once:
#ifndef MY_HEADER_FILE_H
#define MY_HEADER_FILE_H
#include <stdio.h>
void my_function();
#endif /* MY_HEADER_FILE_H */
In this example, the program checks whether the MY_HEADER_FILE_H symbol has been defined using #define. If it has not been defined, then the code between #ifndef and #endif will be included, which in this case is a function declaration for my_function and an inclusion of the standard input/output header file.
If the MY_HEADER_FILE_H symbol has already been defined, then the code between #ifndef and #endif will be skipped. This ensures that the header file is only included once in the compilation process, which can prevent errors and improve the efficiency of the compilation process.
Here’s an example implementation of my_function
:
#include "my_header_file.h"
void my_function() {
printf("Hello, world!\\n");
}
In this implementation, the header file my_header_file.h is included, which contains the declaration for my_function. The implementation of my_function then simply prints “Hello, world!” to the console.
By using #ifndef and #define in the header file, we ensure that the declaration for my_function and the inclusion of the standard input/output header file are only included once in the compilation process.