What is the usage of ifndef in the C language?
#ifndef is one of the conditional compilation directives in C language, which is used to check if a specific identifier has been defined. If it has not been defined, the code in the conditional compilation directive will be executed; otherwise, the code block will be skipped.
The usage of #ifndef is as follows: If the identifier is not defined, execute the code block.
An identifier is a combination of letters, numbers, and underscores used to represent a macro definition.
When encountering the #ifndef directive, the compiler will first check if the identifier has already been defined. If not, it will execute the code block within the conditional compilation directive; otherwise, it will skip that code block.
This usage is commonly employed to prevent duplicate inclusion of header files and selectively compile code based on different macro definitions. For example:
#ifndef MYHEADER_H
#define MYHEADER_H
// Content of the header file
The end of the code.
This code first checks if MYHEADER_H has been defined. If it has not been defined, it will execute the subsequent code block and define the MYHEADER_H macro, indicating that the header file has been included once. If it is included again in the future, it will be skipped. This helps prevent errors caused by multiple inclusions of the same header file.