In C Language, the #error directive is a preprocessor directive that allows us to generate a compilation error with a custom error message.
It is useful for ensuring that certain conditions or requirements are met during compilation.
When an error is encountered, the `#error` directive halts the compilation process and displays the specified error message.
The `#error` directive is typically used within conditional compilation directives such as #ifdef, #ifndef, #if, #elif, #else.
#error error_message
Where "error_message" is the custom error message that we can display when the directive is encountered during preprocessing.
#include <stdio.h> #ifndef MAX_SIZE #error "MAX_SIZE macro is not defined. Please define MAX_SIZE before compiling." #endif int main() { printf("Program executed.\n"); return 0; }
#error "MAX_SIZE macro is not defined. Please define MAX_SIZE before compiling.
the program checks if the MAX_SIZE macro is defined.
If it is not defined, the #error directive is triggered, causing the compilation to fail with the specified error message: "MAX_SIZE macro is not defined.
Please define MAX_SIZE before compiling."
#if __GNUC__ < 13 #error "This program requires GCC version 13 or higher." #endif #include <stdio.h> int main() { printf("Program executed.\n"); return 0; }
#error This program requires GCC version 13 or higher.
the program checks if the compiler's version supports the 13 or higher.
If it doesn't (as indicated by the value of __GNUC__), the #error directive is triggered, displaying the error `This program requires GCC version 13 or higher.`.
#include <stdio.h> #ifndef __linux__ #error "This program will not compiled on non Linux system." #endif int main() { printf("Hello, Linux!\n"); return 0; }
The `#error` directive ensures the program is compiled only on a Linux system.
If the `__linux__` macro is not defined (indicating compilation on a non-Linux system), the compilation process halts with the specified error message.
#error "This program will not compiled on non Linux system."
These examples demonstrate how "#error" can be used to enforce specific conditions or requirements during the compilation process, ensuring that the program is compiled under the desired constraints.